← Python lessons

String Formatting

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A string is a text value written inside matching quotes. An f-string lets you insert values into text by putting them 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.

print("Greedy" + " " + "Pig")

This prints Greedy Pig. The " " in the middle adds the space.

Repeating strings with *

* repeats a string a whole number of times.

print("ab" * 3)print("-" * 10)

This prints ababab, then a line of ten dashes. The number can be a variable too: "#" * step.

f-strings

Put an f before the opening quote, then wrap any variable in {}.

name = "Alice"score = 38print(f"{name} has {score} points")

Python inserts the values of name and score into the message. Numbers work too — you do not need to turn them into text first.

Calculations inside the braces

The braces can hold a calculation. Python works it out, then inserts the result.

score = 10print(f"After one more point: {score + 1}")

This prints After one more point: 11. The value of score is still 10.

See also: Printing, Variables.

Your turn

Add one line: use an f-string to print the message shown in the goal.

🎯 Goal — make it print exactly:
Bob scored 42 points
name = "Bob"score = 42# add one print that uses an f-string

Advanced reading

  • Number formatting — show two decimal places, pad columns and add thousands separators.