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
- Double quotes
"..."and single quotes'...'are the same. Choose one and use it everywhere. - Triple quotes
"""..."""can hold several lines. len(menu)counts its characters: 9. The space is counted too.
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 |
- To take one character, write its index in square brackets:
menu[0]isC. Indexes start at 0, so the last character is atlen(menu) - 1, which is index 8. - A negative index counts from the end:
menu[-1]isw, the last character. menu[9]doesn't exist, and Python refuses it withIndexError: string index out of range.
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
menu[start:stop]takes from indexstartup to beforestop. Somenu[0:4]takes indexes 0, 1, 2, 3.- If you leave
startempty, it means from the beginning. If you leavestopempty, it means up to the end. menu[-4:]means the last four characters. This is useful when the length of the text can change.- Slicing gives no error when a number is past the end of the text:
menu[2:100]stops at the end and givesld brew. [::-1]reverses the text. The third number, after the second colon, is the step: how many characters to move each time. A step of -1 means going backwards, one at a time.
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']
.upper()gives the text in all capital letters,.lower()in all small letters, and.strip()without the spaces at both ends.len()is not a method. It is an ordinary function, so the text goes inside the parentheses:len(order), notorder.len()..replace(old, new)replaces everyoldwithnew..split(", ")cuts the text at every", "(a comma, then a space) and gives a list (a row of values). Print writes it with square brackets and single quotes..join()does the opposite of cutting: it joins the items of a list into one text. You call it on the separator (the text placed between the items of the list), so the separator comes before the dot. Here it is one space:" ".join(["coffee", "tea", "toast"])givescoffee tea toast.
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!
{total:,}adds a thousands separator. The separator is a comma, as in English. Many countries use dots between the thousands. For that style, replace the commas with dots using.replace(",", ".").{per_person:.2f}writes exactly 2 digits after the dot, rounded: 2966.6666666666665 becomes2966.67.- Be careful when you use
,and.2ftogether, then replace the commas with dots:f"{per_person:,.2f}".replace(",", ".")gives2.966.67, with two confusing dots. Swap commas and dots in one step with.translate(str.maketrans(",.", ".,")), which gives2.966,67. For a real application, there is a library called babel (ready-made code that does not come with Python). It writes each country's money format for you:format_currency(per_person, "USD", locale="en_US")gives$2,966.67."USD"is the code for US dollars, andlocale="en_US"picks the US way of writing numbers. {name.upper()}runs the method first, then inserts the result.
📌 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
- Not keeping a method's result.
menu.upper()alone changes nothing. Store the result (menu = menu.upper()) or print it right away (print(menu.upper())). - Using
lenas the last index.menu[9]on a text of 9 characters is anIndexError. The last character ismenu[8]ormenu[-1]. - Calling
.join()on the list.words.join(" "), wherewordsis a list, fails withAttributeError: 'list' object has no attribute 'join'. The right way is" ".join(words). - Forgetting the parentheses.
print(menu.upper)doesn't run the method. It only writes<built-in method upper of str object at 0x...>.
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.