Strings in Python

A string is text between quotes, and len() counts its characters. Indexes (the position number of each character) start at 0. Negative indexes count from the…

In the operators lesson, an $89 bill shared by 3 people gave 29.666666666666668. On a receipt, a number like that only confuses the customer. Making that number tidy, writing the customer's name budi as BUDI, and taking Cold from Cold brew: all of these are work on text. In Python, text is called a string (type str): a row of characters (letters, digits, spaces or punctuation) between quotes.

Think of a string as a menu board made of small tiles in a row. Each tile holds one character: C, o, l, d and so on. Each tile has a number. You can read one tile, or copy a few tiles that are next to each other. But the tiles are glued in place, so you can't replace one. If you want different text, you make a new board.

Making a string

Three ways to write a string, and then its length:

menu = 'Cold brew'
shop = "Mr. Darto's Coffee Stall"
receipt = """Cold brew x3
Sweet tea x4"""

print(len(menu))   # 9

Indexes: a number for each character

Each character in menu has a position number called an index:

Character C o l d space b r e w
Index 0 1 2 3 4 5 6 7 8
Negative index -9 -8 -7 -6 -5 -4 -3 -2 -1

Slicing: taking a part

Slicing takes a part of a string. Still with the same menu:

print(menu[0:4])    # Cold
print(menu[5:])     # brew
print(menu[-4:])    # brew
print(menu[:4])     # Cold
print(menu[::-1])   # werb dloC

String methods

A method is a function attached to a value. You call it (run it) with a dot: value.method_name(). Some examples:

order = "cold brew, sweet tea, fried rice"

print(order.upper())                     # COLD BREW, SWEET TEA, FRIED RICE
print(len(order))                        # 32
print(order.replace("tea", "iced tea"))  # cold brew, sweet iced tea, fried rice
print(order.split(", "))                 # ['cold brew', 'sweet tea', 'fried rice']

Strings can't be changed

Try to make menu uppercase:

menu = "Cold brew"
menu.upper()
print(menu)          # Cold brew

menu = menu.upper()
print(menu)          # COLD BREW

Strings are immutable: their contents can't be changed, like the tiles glued onto the menu board. A method like .upper() doesn't change menu. It makes a new string. If you don't store that new string, it is gone right away, so the first print(menu) still writes Cold brew. To keep the result, stick the name menu onto the new string: menu = menu.upper().

Replacing one character directly, with menu[0] = "c", is refused too. The last line of the error means that you can't replace a character inside a str.

Traceback (most recent call last):
  File "/home/darto/stall.py", line 2, in <module>
    menu[0] = "c"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

f-strings with a format spec

Inside the {} of an f-string you can write an expression (code that gives a value, such as a calculation). After a : you can add a format spec, a rule for how to write the value. Here a month's takings of $8,900 are shared by 3 partners:

total = 8900
per_person = total / 3
name = "budi"

print(f"Total: {total:,}")                       # Total: 8,900
print(f"Total: {total:,}".replace(",", "."))     # Total: 8.900
print(f"Per person: {per_person:.2f}")           # Per person: 2966.67
print(f"Hello, {name.upper()}!")                 # Hello, BUDI!

📌 More format specs

print(f"{'Cold':<10}|")   # Cold      |
print(f"{'Cold':>10}|")   #       Cold|
print(f"{'Cold':^10}|")   #    Cold   |
print(f"{7:03}")          # 007
print(f"{0.8745:.1%}")    # 87.5%

<, > and ^ align the text left, right and centre within a width of 10 characters. This is useful for a tidy receipt. The | in the examples only shows where that width ends. 03 adds zeros in front of a number until it is 3 digits long. .1% multiplies the value by 100, then writes one digit after the dot and a percent sign.

⚠️ Text that won't change, and other small slips

TL;DR: A string is text between quotes, and len() counts its characters. Indexes (the position number of each character) start at 0. Negative indexes count from the end (menu[-1] is the last character), and an index out of range is an IndexError. Slicing menu[start:stop] takes a part of the string: it stops before stop, and gives no error when a number is out of range. Methods (functions attached to a value) are called with a dot: .upper(), .replace(old, new) and .split(", ") (which gives a list, a row of values). " ".join(list) joins the items of a list. The text before the dot, here a space, goes between the items. Strings are immutable (they can't be changed): a method makes a new string, so store or print its result. Format specs (rules after the : inside the {} of an f-string): {total:,} for a thousands separator (8,900), {x:.2f} for 2 digits after the dot.

⚡ A number for each character

Write:

menu = "Cold brew"
print(menu[0:4])    # Cold
print(menu[-4:])    # brew

Meaning: Text in Python is called a string. Each character has a position number (an index) that starts at 0, so menu[0] is C. Negative indexes count from the end: menu[-1] is the last character. menu[start:stop] takes from start up to before stop. If stop is empty, it means up to the end.

⚡ Strings can't be changed

Guess first: .upper() gives the text in all capital letters. menu = "Cold brew", then menu.upper(), then print(menu). What gets printed?

Cold brew. .upper() makes a new string, and because it isn't stored, that new string is gone right away.

Meaning: Strings are immutable: their contents can't be changed. .upper() is a method: a function you call with a dot on a value. A method makes a new string, so store its result: menu = menu.upper().

⚡ Cut and join

Write:

order = "cold brew, sweet tea, fried rice"
print(order.split(", "))                 # ['cold brew', 'sweet tea', 'fried rice']

Meaning: .split(", ") cuts the text at every ", " into a list (a row of values). The opposite is .join(). It is called on the separator (the text between the items of the list), which comes before the dot: " ".join(["coffee", "tea", "toast"]) gives coffee tea toast.

⚡ Tidy numbers in an f-string

Write:

total = 8900
per_person = total / 3
name = "budi"

print(f"Total: {total:,}")                       # Total: 8,900
print(f"Per person: {per_person:.2f}")           # Per person: 2966.67
print(f"Hello, {name.upper()}!")                 # Hello, BUDI!

Meaning: After the : inside {} comes a rule for how to write the value: , for a thousands separator, .2f for 2 digits after the dot. {name.upper()} runs the method first, then inserts the result.

What you will learn