Learn

Short lessons with real code you can edit and run on the page.

String Formatting in Python with f-strings

Lesson 6 Python 3.14 Runs in your browser Updated
In short

An f-string is a string with an f before the opening quote and expressions inside curly braces, such as f"Hello, {name}". An expression is any piece of code that produces a value. Python evaluates each expression and puts the result into the text, and a format specifier after a colon controls decimals, padding and alignment.

Key facts

  • Almost any expression works inside the braces of an f-string, not only a variable name, so {a * b} and {name.upper()} are fine.
  • {price:.2f} gives two decimal places and {price:,} adds thousands separators. Combine them as {price:,.2f}.
  • A literal brace is written twice, so {{ prints {.
  • f-strings arrived in Python 3.6. The older % and format() forms still run and still appear in old code.

How do I format a string in Python?

Put an f before the opening quote and the variable in curly braces. Python replaces the braces with the value when the line runs. The older format() method does the same job with more typing.

Python
name = "Ada"
age = 36
print(f"{name} is {age} years old.")
print("{} is {} years old.".format(name, age))
Output
Ada is 36 years old.
Ada is 36 years old.

Notice that age is a number and the f-string still works. No str(), no +. That avoids the TypeError you get from joining text and a number with +.

How do I format a number to 2 decimal places?

Add a format specifier after a colon inside the braces. .2f means a fixed-point number with two decimals, a comma adds thousands separators, % multiplies by 100 and adds a percent sign, and 03d pads a whole number with zeros to a width of three characters.

Python
price = 1234.5
print(f"{price:.2f}")
print(f"{price:,}")
print(f"{price:,.2f}")
share = 0.256
print(f"{share:.1%}")
print(f"{7:03d}")
Output
1234.50
1,234.5
1,234.50
25.6%
007
f-string format specifiers in Python
SpecifierMeaningExampleResult
.2fTwo decimal placesf"{3.14159:.2f}"3.14
,Thousands separatorf"{1234567:,}"1,234,567
.1%Percentage, one decimalf"{0.256:.1%}"25.6%
03dWhole number padded with zerosf"{7:03d}"007
eScientific notationf"{1234.5:e}"1.234500e+03

How do I align and pad text in an f-string?

Put a width after the colon. A <, > or ^ in front of the width aligns the value left, right or center, which is how you line up the columns of a table.

Python
for item, cost in [("Tea", 2.5), ("Sandwich", 6.25), ("Cake", 3)]:
    print(f"{item:<10}{cost:>8.2f}")
print(f"[{'hi':^10}]")
Output
Tea           2.50
Sandwich      6.25
Cake          3.00
[    hi    ]

{cost:>8.2f} combines right alignment, a width of 8 and two decimals, in that order. The for line runs the print once per row.

Can I put expressions in an f-string?

Yes. Almost anything that produces a value can sit between the braces, including math, method calls and function calls. Adding = after the expression prints the expression itself alongside its value, which is a quick way to debug. With =, a string value shows in quotes, so f"{name=}" prints name='ada'.

Python
a = 6
b = 7
name = "ada"
print(f"{a} times {b} is {a * b}")
print(f"Hello, {name.upper()}!")
print(f"{a=}, {b=}")
Output
6 times 7 is 42
Hello, ADA!
a=6, b=7

What are %s, %d and format() in Python?

They come from two older ways to format strings in Python. In the % form, %s turns any value into text and %d shows a number as a whole number. The format() method fills empty, numbered or named braces. You will see them in older code and online answers; write f-strings in new code.

Python
name = "Ada"
print("Hello, %s. You are %d." % (name, 36))
print("Hello, {0}. You are {1}.".format(name, 36))
print(f"Hello, {name}. You are {36}.")
Output
Hello, Ada. You are 36.
Hello, Ada. You are 36.
Hello, Ada. You are 36.

Common mistakes with f-strings in Python

Each of these f-string mistakes is a small fix once you know what to look for.

  • Forgetting the f. "Hello, {name}" prints the braces and the word name, exactly as typed.
  • Typing one brace to print a brace. Double it, so f"{{" prints {.
  • ValueError: Precision not allowed in integer format specifier. .2d asks for decimals on a whole number. Use .2f, or drop the precision.
  • Reusing the outer quote inside the braces on Python 3.11 or older. It is a SyntaxError there, so use the other kind of quote. Python 3.12 and later accept it.
Python
name = "Ada"
print("Hello, {name}!")
print(f"Hello, {name}!")
print(f"Braces: {{literal}} and {name}")
Output
Hello, {name}!
Hello, Ada!
Braces: {literal} and Ada
Python
price = 5
print(f"{price:.2d}")
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(f"{price:.2d}")
            ^^^^^^^^^^^
ValueError: Precision not allowed in integer format specifier

Exercise

Complete the print line so the program prints Total: $1,234.50. Use one f-string that adds the dollar sign, the thousands separator and exactly two decimal places.

Python
price = 1234.5

print()
Output
Show the solution
price = 1234.5

print(f"Total: ${price:,.2f}")

Quiz

This quiz has 5 questions. Pick an answer to see why it is right or wrong.

  1. 1What does this program print?

    x = 3.14159
    print(f"{x:.2f}")
  2. 2What does this program print?

    name = "Ada"
    print("Hi, {name}")
  3. 3Which f-string produces 1,000,000?

  4. 4What does this program print?

    n = 5
    print(f"{n=}")
  5. 5How do you put a literal { inside an f-string?

Frequently asked questions

How do I format strings in Python?
Use an f-string. Put f before the opening quote and the value in braces, as in f"Hello, {name}". Add a specifier after a colon for decimals or width, such as f"{price:.2f}".
What are %s, %d and %f in Python?
They are placeholders in the older % formatting style. %s turns any value into text, %d shows a number as a whole number and %f as a decimal number. f-strings have largely replaced them, but they still work.
How do I format a number to 2 decimal places in Python?
Write f"{value:.2f}". The f means fixed point and the .2 means two digits after the decimal point, so 3.14159 becomes 3.14.
How do I put a variable inside a string in Python?
Use an f-string, as in f"Total: {total}". The variable can be any type, so there is no need to convert numbers with str() first.
Can I use quotes inside an f-string?
Yes. Since Python 3.12 the same quote character can appear inside the braces, and in any version you can use the other kind of quote inside.
What does the = sign do in an f-string?
f"{x=}" prints both the expression and its value, for example x=5, and strings show in quotes. It was added in Python 3.8 for debugging.