Text: Strings and f-strings
Most of what a program produces is text for a person: a message, a receipt, a report. Python calls a piece of text a string, and it gives strings dozens of built-in tools. This page covers the handful used every day, plus the one way to build a sentence out of values that this book uses everywhere: the f-string.
Picture a printed label. You can print a new label in capital letters, or a trimmed one, but you cannot change the ink on the label you already have. Strings in Python work like that, and the last section of this page explains why it matters.
Quotes
A string can be written in double quotes or single quotes; they mean exactly the same thing. This book uses double quotes. Both exist so that a string can contain the other kind: "it's" holds an apostrophe without any trouble, because the apostrophe is not the quote that closes the string.
Joining and Measuring
A plus sign joins two strings into one, as the last page showed. The len function counts the characters in a string, spaces included. The string in the session below has two spaces before Coffee and two after beans, which is why its length is 16 rather than 12.
>>> item = " Coffee beans " >>> len(item) 16
Methods: Things a String Can Do
Strings come with built-in actions called methods. You use one by writing the string, or a name that points at it, then a dot, then the method's name and brackets. The dot means: ask this value to do something. The session below tries five of the most useful.
strip removes spaces from both ends. upper and lower change the case. split cuts a string into pieces wherever a separator appears, and gives back a list of the pieces; lists are Chapter 4's subject. replace swaps one piece of text for another.
>>> item.strip()
'Coffee beans'
>>> item.upper()
' COFFEE BEANS '
>>> item.strip().lower()
'coffee beans'
>>> "bread, milk, eggs".split(", ")
['bread', 'milk', 'eggs']
>>> "it's".replace("it", "that")
"that's"
The third line shows that methods can be chained: strip first, then lower-case the result. Each method hands back a new string, and the next dot asks that new string to do something.
f-strings
Joining text with plus signs gets clumsy fast, and it fails outright with numbers. The session below tries to join the text Total to the number 42 and gets the same TypeError as on the first page of this chapter.
>>> "Total: " + 42
Traceback (most recent call last):
File "<python-input-7>", line 1, in <module>
"Total: " + 42
~~~~~~~~~~^~~~
TypeError: can only concatenate str (not "int") to str
The modern answer is the f-string: a string with the letter f written just before the opening quote. Inside it, anything in curly braces is worked out and put into the text. f"Total: {42}" gives the text Total: 42. Without the f, the braces are printed as they are, which is a common slip.
Inside the braces you can also say how a value should look. A colon, then point-two-f, means "show this number with exactly two decimal places". That is how the rounded-for-display total on the last page became 12.60.
item = "coffee" price = 4.2 print(f"One {item} costs {price:.2f}.")
One coffee costs 4.20.
Strings Do Not Change
Look back at the methods session. After item.upper() printed the capitals, item itself was still the original mixed-case text with its spaces. String methods never change the string they are called on. They make a new string and hand it back. If you want to keep the result, tie a name to it: item = item.strip() points the name at the trimmed version.
- "
name.upper()changed name." It made a new string and handed it back. The name still points at the original until you reassign it. - "
"Total: " + 42should just work." Plus cannot join text to a number. An f-string puts the number into the text for you. - "The f before the quotes is a typo." It is what makes the braces work. Leave it out and the braces and their contents are printed literally.
- "
splitgives back a string." It gives back a list of strings, one for each piece. Chapter 4 shows what to do with a list.
- Nearly every program ends in text a person reads. f-strings get that text right on the first try, numbers and decimal places included.
strip,lowerandsplitare the first tools for cleaning messy input from people and files, and they appear in almost every later chapter.
Knowledge Check
What does " hi ".strip() give?
'hi', with the spaces at both of its ends removed'hi ', with only the spaces on the left removed' hi ', unchanged, because strip needs a count2, the number of letters left after stripping
After name = "Ada" and then name.upper(), what does name point at?
"ADA", because upper changed the string in place"Ada", because upper returned a new string- Nothing, because upper deleted the old string
- An error, because upper needs a name inside the brackets
What does f"Total: {amount:.2f}" show when amount is 7.5?
Total: {amount:.2f}, with the braces printed as typedTotal: 7.5, because the formatting is ignored for floatsTotal: 8, rounded to the nearest whole numberTotal: 7.50, shown with exactly two decimal places
What does "bread, milk".split(", ") give back?
- The text
bread milk, with the comma removed - A list of two strings: bread and milk
- The number 2, the count of items in the text
- An error, because split only works on spaces
You got correct