String Formatting
A string is a text value. You can write one inside matching quotes. An f-string lets you insert values into text by putting expressions inside {}.
Making strings
name = "Alice"
said = 'Alice said "bank it"'
print(name)
print(said)
Single or double quotes both work, as long as you match them. Use one kind when the other kind appears inside the text.
Joining strings with +
+ glues strings together. It only works string-to-string — you can't + a
string and a number:
first = "Greedy"
second = "Pig"
print(first + " " + second)
f-strings
Put an f before the opening quote, then wrap any variable in { }:
name = "Alice"
score = 38
print(f"{name} has {score} points")
Python inserts the values of name and score into the message. An f-string can display numbers as well as strings; you do not need to convert the number to text first.
Optional: calculations inside the braces
An f-string can also display the result of a calculation:
score = 10
print(f"After one more point: {score + 1}")
Python calculates score + 1, then inserts the result into the message. You do not need calculations inside braces for the first greeting exercise.
See also: Printing, Variables.
Your turn
Add one line: use an f-string to print the message shown in the goal.
name = "Bob"
score = 42
# add one print that uses an f-string
Expected output
Bob scored 42 points
Choose how a number is displayed
A format specifier goes after a colon inside the braces.
:.2f displays a number with two digits after the decimal point.
price = 3.5
print(f"Price: ${price:.2f}")
print(price)
The first line is Price: $3.50; the second is 3.5.
Formatting creates text for display without changing price.
round(price, 2) alone does not guarantee two displayed decimal places.
Your turn: format a price
Print the label and amount with exactly two decimal places.
total = 12.5
# Print total in the message using :.2f.
Expected output
Total: $12.50
For converting data to another type before using it, see Data Validation. Formatting a display and validating data are different jobs.
Practise this in the free Python course, where every exercise checks your code instantly.