← Python from Scratch
Lesson 16 of 78 · 10 XP
String formatting
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
The handiest way to put values into text is f-strings: you write f before the quote and put the values in curly braces:
name = "Roma"
age = 20
print(f"{name}, you are {age}") # Roma, you are 20
print(f"In a year: {age + 1}") # you can do arithmetic inside the braces
After a colon you give the format:
price = 45
print(f"{price:.2f}") # 45.00 — two decimal places
print(f"{3.14159:.1f}") # 3.1
print(f"{7:>4}") # ' 7' — right-align in 4 characters
print(f"{1234567:,}") # 1,234,567 — thousands separator
People used to use "{} and {}".format(a, b) and %. You'll see them in old code, but write f-strings in new code.
Task. Read a product name, a price (a fractional number) and a quantity (a whole number). Print a receipt in the form Total: Bread x 3 = 135.00 — the amount with two decimal places.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.