Strings

Strings in Python are Unicode by default, and are immutable.

String are lists of characters, so whatever operations can be performed on lists can be performed on strings.

endswith()

Examples

>>> 'hello'.endswith('o')
True
>>> 'hello'.endswith('ello')
True
>>>

Formatting Strings

Setting Column Alignment and Width

Use {:<10} for left alignment (note < is an arrow pointing to the left), max width 10:

names = 'Julian Bob PyBites Dante Martin Rodolfo'.split()
countries = 'Australia Spain Global Argentina USA Mexico'.split()

for name,country in zip(names, countries):
    print("{:<10} {}".format(name, country))

Output:

Julian     Australia
Bob        Spain
PyBites    Global
Dante      Argentina
Martin     USA
Rodolfo    Mexico

Same as above, with right alignment:

for name,country in zip(names, countries):
    print("{:>10} {}".format(name, country))

Output:

 Julian Australia
    Bob Spain
PyBites Global
  Dante Argentina
 Martin USA
Rodolfo Mexico

Additional Formatting Examples

Code:

# output type decimal
Formatted = "{:d}"
print(Formatted.format(7000))

# comma separated decimal
Formatted = "{:,d}"
print(Formatted.format(7000))

# centered, 15 wide, decimal
Formatted = "{:^15,d}"
print(Formatted.format(7000))

# fill = "*",centered, 15 wide, decimal
Formatted = "{:*^15,d}"
print(Formatted.format(7000))

# fill = "*",centered, 15 wide, decimal, 2 decimal places
Formatted = "{:*^15.2f}"
print(Formatted.format(7000))

# fill = "*", right aligned, hexadecimal
Formatted = "{:*>15X}"
print(Formatted.format(7000))

# fill = "*",left aligned, alt display, 15 wide, hexadecimal
Formatted = "{:*<#15x}"
print(Formatted.format(7000))

# specify index numbers of fields
Formatted = "A {0} {1} and a {0} {2}."
print(Formatted.format("blue", "car", "truck"))

Output:

7000
7,000
     7,000
*****7,000*****
****7000.00****
***********1B58
0x1b58*********
A blue car and a blue truck.

Indexing Strings

Negative indexing indexes from the back of the string.

Examples x[-1] gets the last letter of a string.

x[-4:-2] gets all of the characters from the 4th last to the 2nd last positions:

>>> my_var = 'coolness'
>>> my_var[-4:-2]
'ne'