Strings and f-strings

Text in Python is a string, written in quotes, joined with + and tidied with methods such as strip() and title(), and an f-string drops values into text, with :.2f to show money to two decimal places.

Novice · Python · Updated

By

After this lesson you can

  • Join, repeat, measure and tidy strings with +, *, len() and the methods strip(), title(), upper(), lower() and replace()
  • Build text with an f-string, using :.2f to show money with two decimal places

Key takeaways

  • A string is text in single or double quotes. + joins strings, * repeats one, and len() counts its characters.
  • A method is an action a value can do, written after a dot, such as name.strip(). String methods give back a new string and leave the original as it was.
  • Joining text and a number with + stops with a TypeError. An f-string, f"Total {total}", puts values into text instead.
  • Inside an f-string's braces, :.2f shows a number with exactly two decimal places, the way money is written, and \n in any string starts a new line.

Programs talk to people in text: a receipt, a message that says an order is ready, a name on a screen. Most of the bugs people notice first are text bugs: a name in the wrong case, a missing space, a price that says $13.0. This lesson covers the tools that get text right, and you'll use them in nearly every program you write.

The example is the snack bar at Starlight Cinema, which prints receipts and calls out each customer's name when their order is ready.

Text in quotes

Python calls a piece of text a string: a string of characters, one after another, like beads on a string. You write one in quotes, single or double; 'Maya' and "Maya" are the same string. Pick double quotes when the text has an apostrophe in it, as in "Maya's order".

Two math operators work on strings too. + joins two strings into one (joining is called concatenation), and * repeats a string:

title = "Starlight" + " " + "Cinema"
line = "-" * 16
print(title)
print(line)
print(len(title))
Starlight Cinema
----------------
16

len() (read "length") counts a string's characters, the space included: 9 letters, a space and 6 more make 16.

Tidying text with methods

At the counter, customers type their own names, and they type them every way: "maya", "MAYA", " maya " with spaces around it. The snack bar wants Maya every time.

A method is an action a value can do. You write it after the value with a dot, then parentheses: name.strip() is read "name dot strip". Strings come with many methods; here are five:

print("  maya  ".strip())
print("maya".title())
print("maya".upper())
print("POPCORN".lower())
print("Small soda".replace("Small", "Large"))
maya
Maya
MAYA
popcorn
Large soda

strip() takes the spaces off both ends, title() gives every word a capital first letter, upper() and lower() change every letter, and replace() swaps one piece of text for another.

A method gives back a new string and leaves the original as it was; a string can't be changed once it's made. So to keep the tidy version, assign it, and two methods can run one after the other:

name = "  maya  "
name.strip()
print("[" + name + "]")
name = name.strip().title()
print("[" + name + "]")
[  maya  ]
[Maya]

The square brackets show where the string starts and ends. The second line tidied a copy and threw it away. The fourth line strips the spaces, gives the result a capital letter, and stores that in name.

Text and numbers don't mix with +

The receipt needs a line such as Total: $28.89. Joining the text and the total with + looks right:

total = 28.89
print("Total: quot; + total)

Python stops with TypeError: can only concatenate str (not "float") to str. str is Python's name for a string, and + joins two strings or adds two numbers; it won't guess which you meant with one of each. Giving print() two values, as in print("Total: quot;, total), runs, but print() puts a space between its values: Total: $ 28.89.

f-strings: values dropped into text

A form letter has blanks: "Dear ____, your order is ready." An f-string (read "f-string") is a string with blanks. Put an f right before the opening quote, and write each value in braces, {}, where it goes:

name = "Maya"
total = 28.89
print(f"Order for {name}: ${total}")
Order for Maya: $28.89

Python fills in each pair of braces with the value inside it, a number turned into text, with no + and no spaces you didn't ask for. The braces can hold a calculation too, such as {3 * 6.50}.

Money needs one more thing. A float drops the zeros it doesn't need, so 13.0 shows as 13.0, and a receipt needs 13.00. After the value, inside the braces, :.2f (read "two decimal places") shows a number with exactly two:

subtotal = 13.0
print(f"Subtotal: ${subtotal}")
print(f"Subtotal: ${subtotal:.2f}")
print("Starlight Cinema\nSnack Bar")
Subtotal: $13.0
Subtotal: $13.00
Starlight Cinema
Snack Bar

The last line shows \n (read "backslash n"), a newline: inside any string, it starts a new line.

Do it: call out a finished order

When an order is ready, the snack bar's screen shows the order and calls the customer's name in capitals. The name comes from what the customer typed, spaces and all.

  • name: the name the customer typed, " maya ", with spaces around it and no capital.
  • popcorns: how many popcorns are in the order, 2.
  • total: the order's total, 13.9.

Your job: print exactly two lines:

  • first, Order for Maya: 2 popcorns, $13.90: the name with no spaces around it and a capital first letter, the number of popcorns, and the total with two decimal places;
  • then, MAYA, YOUR ORDER IS READY!: the tidy name in capital letters, a comma, and the rest in capitals too.

Worked through: " maya " stripped and given a capital is Maya; 13.9 with two decimal places is 13.90; and Maya in capitals is MAYA. So the screen shows Order for Maya: 2 popcorns, $13.90, then MAYA, YOUR ORDER IS READY!.

Practiced live on the lesson page: write the Python right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Strings are how every program talks to people, and an f-string is the tidy way to put your values into what it says.

Key terms

Related