Skip to content
PythonStrings and Textbeginner18 min read

String Formatting and f-Strings

Learn how to insert variables and expressions into strings, format numbers, control decimal places, align text, and produce readable output using Python f-strings.

In this lesson, you will learn

  • ✓Explain what f-strings are and how the f or F prefix enables expression interpolation.
  • ✓Insert variables, arithmetic expressions, and method results into formatted strings.
  • ✓Use format specifiers to control decimal places, thousands separators, percentages, and text alignment.
  • ✓Display literal curly braces and distinguish string formatting from changing the original variable.
  • ✓Trace f-string examples, predict their exact output, and solve practical formatting problems.

1. What are f-strings?

An f-string, short for formatted string literal, is a string prefixed with f or F immediately before its opening quotation mark. It allows you to place Python expressions inside curly braces, { and }. Python evaluates those expressions and inserts their formatted values into the resulting string.

Without an f-string, you might need string concatenation or explicit type conversion to combine text and numbers. An f-string is usually easier to read because the surrounding text and the values appear together.

The f prefix must come before the opening quotation mark. Both single-quoted and double-quoted f-strings are valid.

Insert a variable into a string

Insert a variable into a string
python
name = 'Ravi'
score = 88
print(f'{name} scored {score}.')
Output
Ravi scored 88.

The f before the opening quote tells Python that this is a formatted string literal. Python evaluates {name} and inserts the value 'Ravi'. It evaluates {score} and inserts the integer value 88. The text outside the curly braces, including the space and final period, remains unchanged. The final string is passed to print(), which displays it.

Note

Write the prefix directly before the opening quote: f'Hello, {name}'. Writing f 'Hello, {name}' does not create an f-string and is not valid syntax as a standalone expression.

2. Insert expressions, not just variables

The expression inside an f-string's curly braces can be a variable, an arithmetic expression, a comparison, or a method call. Python evaluates the expression and inserts its result into the string.

This means you do not need to create a separate variable for every simple calculation. However, if an expression becomes difficult to understand, calculating it beforehand can make your code clearer.

Perform arithmetic inside an f-string

Perform arithmetic inside an f-string
python
a = 10
b = 5
print(f'Sum: {a + b}')
print(f'Difference: {a - b}')
print(f'Product: {a * b}')
Output
Sum: 15 Difference: 5 Product: 50

Python evaluates a + b as 15, a - b as 5, and a * b as 50. The resulting numbers are inserted into their respective strings. The calculations do not modify a or b.

Note

Curly braces tell Python to evaluate an expression. Ordinary text outside those braces is copied into the resulting string.

3. Format decimal numbers with precision

Sometimes a number needs a particular display format. For example, prices usually display two digits after the decimal point, even when the value is a whole number.

A format specifier follows an expression after a colon inside its curly braces. The .2f specifier means fixed-point formatting with two digits after the decimal point. Similarly, .3f requests three digits after the decimal point.

The f in .2f is part of the format specifier; it is different from the f prefix at the beginning of the formatted string.

Display a price with two decimal places

Display a price with two decimal places
python
price = 12.5
print(f'Price: ${price:.2f}')
Output
Price: $12.50

The dollar sign is ordinary text in the f-string. The expression price is formatted using .2f. The result displays two digits after the decimal point, so 12.5 appears as 12.50. Formatting the value does not assign a new value to price.

Caution

A format specifier controls how a value is represented in the resulting string; it does not change the variable's stored value. Also, floating-point rounding can affect the displayed final digit, so do not assume formatting is equivalent to storing a rounded number.

4. Format large numbers and percentages

Python provides format specifiers for common display requirements. A comma can group large numbers into thousands, while the percent format multiplies a numeric value by 100 for display and adds a percent sign.

Use the format specifier that matches the intended output. These specifiers affect presentation, not the underlying numeric variable.

Add thousands separators

Add thousands separators
python
population = 1250000
print(f'Population: {population:,}')
Output
Population: 1,250,000

The comma in the format specifier groups the integer digits into thousands. The integer stored in population remains 1250000.

Note

A percentage value is commonly stored as a fraction: 0.5 represents 50%, and 1.0 represents 100%. The % format performs the conversion for display.

5. Control text alignment and width

Formatted strings can also align text and numbers in columns. A width specifies a minimum field width, measured in characters. If the value is shorter than that width, Python adds padding. If the value is longer, Python does not truncate it automatically.

The alignment characters are < for left alignment, > for right alignment, and ^ for center alignment. For strings, left alignment is the default. For many numeric formats, right alignment is the default.

Left-align text

Left-align text
python
name = 'Ravi'
print(f'|{name:<10}|')
Output
|Ravi |

The format specifier <10 sets a minimum width of 10 characters and left-aligns the value. Ravi uses four characters, so six spaces are added after it. The vertical bars make the padding visible; they are part of the printed text.

Note

When exact output matters, spaces count as characters. The bars in these examples are included only to make leading and trailing spaces easier to see.

6. Display literal curly braces

Curly braces normally mark expressions in an f-string. If you want to display actual curly braces as text, double them: use {{ to display { and }} to display }.

This is useful when printing examples of code, configuration fragments, or other text that contains braces.

Print curly braces

Print curly braces
python
name = 'Ravi'
print(f'{{Hello, {name}}}')
Output
{Hello, Ravi}

The doubled opening braces {{ produce one literal opening brace. The expression {name} is evaluated normally and inserts Ravi. The doubled closing braces }} produce one literal closing brace.

Caution

Do not use a single unmatched curly brace as ordinary text inside an f-string. Double literal braces so Python does not mistake them for replacement-field syntax.

7. Understand expression evaluation and conversion

Python evaluates expressions inside an f-string when it executes that formatted string. Replacement fields are evaluated from left to right. The result is then formatted and inserted into the final string.

You can also request a particular conversion. The !s conversion uses str(), while !r uses repr(). The latter is helpful for debugging because it often makes quotes and special characters visible. These conversions are optional; ordinary f-strings already format common values appropriately.

The debug form {expression=} can display the expression together with its value. This feature is available in Python 3.8 and later.

Trace evaluation order

Trace evaluation order
python
a = 4
b = 6
result = a + b
print(f'{a} + {b} = {result}')
Output
4 + 6 = 10

Python assigns 4 to a and 6 to b. It evaluates a + b and stores 10 in result. When the f-string is evaluated, Python inserts the values of a, b, and result into the appropriate positions.

Note

For beginner projects, prioritize straightforward expressions and readable formatting. Some advanced f-string syntax differs between older Python versions and Python 3.12+, so check the Python version when using newer expression syntax.

8. Step-by-step dry run

A dry run means tracing the program without skipping any statement. Track the values assigned to variables, then work out the exact text produced by each f-string.

Build a formatted receipt

Build a formatted receipt
python
item = 'Notebook'
price = 49.5
quantity = 2
total = price * quantity
print(f'Item: {item}')
print(f'Price: Rs. {price:.2f}')
print(f'Quantity: {quantity}')
print(f'Total: Rs. {total:.2f}')
Output
Item: Notebook Price: Rs. 49.50 Quantity: 2 Total: Rs. 99.00

First, item is assigned 'Notebook', price is assigned 49.5, and quantity is assigned 2. Next, total is calculated as 49.5 * 2, which equals 99.0. The first f-string inserts the item name. The second f-string displays the price with two decimal places. The third f-string inserts the integer quantity. The final f-string displays 99.0 as 99.00.

Note

Formatting changes the text that is displayed, not the values stored in item, price, quantity, or total.

9. Practical use and edge cases

F-strings are useful for receipts, reports, status messages, logs, summaries, and readable command-line output. They help present values consistently without mixing many concatenation operations together.

Test values that are likely to expose formatting mistakes: zero, negative numbers, large numbers, decimal values that require rounding, and strings that are shorter or longer than the requested width.

Remember that a width is a minimum, not a maximum. A value longer than the specified width remains intact. Also remember that formatting a value does not update the original variable.

Format zero and a negative number

Format zero and a negative number
python
balance = 0
change = -12.345
print(f'Balance: {balance:.2f}')
print(f'Change: {change:.2f}')
Output
Balance: 0.00 Change: -12.35

Zero is displayed with two decimal places as 0.00. The negative sign is preserved, and the value is formatted to two decimal places. The negative value is displayed as -12.35.

Caution

F-strings evaluate Python expressions. Do not treat untrusted input as executable code or build dynamic code evaluation with eval() merely to format text. For ordinary formatting, insert values directly into an f-string.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Forgetting the f prefix.

Why it happens: Without the f prefix, Python treats braces as ordinary string characters instead of evaluating the expression inside them.

Incorrect Approach
script.py
python
Forgetting the f prefix.
Correct Solution
script.py
python
Write f immediately before the opening quote. Without it, {name} is treated as ordinary string text rather than a replacement field.

Key takeaway: Write f immediately before the opening quote. Without it, {name} is treated as ordinary string text rather than a replacement field.

#2 Using parentheses instead of curly braces for interpolation.

Why it happens: F-string expressions are placed inside curly braces; parentheses only group an expression and do not interpolate it into the text.

Incorrect Approach
script.py
python
Using parentheses instead of curly braces for interpolation.
Correct Solution
script.py
python
Use {expression} inside an f-string. Parentheses are used for grouping expressions or calling functions, not for f-string replacement fields.

Key takeaway: Use {expression} inside an f-string. Parentheses are used for grouping expressions or calling functions, not for f-string replacement fields.

#3 Expecting .2f to change the original variable.

Why it happens: A format specifier changes how a value is displayed in the resulting string; it does not mutate or reassign the original variable.

Incorrect Approach
script.py
python
Expecting .2f to change the original variable.
Correct Solution
script.py
python
Remember that .2f controls the formatted representation. Assign a separately rounded result if you need to store a rounded numeric value.

Key takeaway: Remember that .2f controls the formatted representation. Assign a separately rounded result if you need to store a rounded numeric value.

#4 Confusing the f-string prefix with the f in .2f.

Why it happens: The f prefix enables interpolation, while .2f is a numeric format specifier meaning fixed-point display with two digits after the decimal point.

Incorrect Approach
script.py
python
Confusing the f-string prefix with the f in .2f.
Correct Solution
script.py
python
The initial f activates interpolation. The f in a format specifier such as .2f requests fixed-point number formatting.

Key takeaway: The initial f activates interpolation. The f in a format specifier such as .2f requests fixed-point number formatting.

#5 Expecting a width to truncate long text.

Why it happens: A field width sets a minimum display width, not a maximum, so longer text is displayed in full.

Incorrect Approach
script.py
python
Expecting a width to truncate long text.
Correct Solution
script.py
python
Treat the width as a minimum field size. Longer values remain intact unless you explicitly apply a truncation operation.

Key takeaway: Treat the width as a minimum field size. Longer values remain intact unless you explicitly apply a truncation operation.

#6 Using single braces when the output needs literal braces.

Why it happens: Single braces mark replacement fields; double braces {{ and }} are used when literal braces must appear in the output.

Incorrect Approach
script.py
python
Using single braces when the output needs literal braces.
Correct Solution
script.py
python
Double literal braces: {{ produces {, and }} produces }.

Key takeaway: Double literal braces: {{ produces {, and }} produces }.

#7 Assuming the percent specifier simply appends a percent sign.

Why it happens: The % format type scales a numeric value by 100 for display, so supply a fractional value such as 0.25 to display 25%.

Incorrect Approach
script.py
python
Assuming the percent specifier simply appends a percent sign.
Correct Solution
script.py
python
Remember that percentage formatting multiplies the value by 100 for display before adding the percent sign.

Key takeaway: Remember that percentage formatting multiplies the value by 100 for display before adding the percent sign.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is an f-string in Python?
Answer:
An f-string, or formatted string literal, is a string prefixed with f or F. It allows Python expressions inside curly braces. Python evaluates those expressions and inserts their formatted results into the resulting string. For example, name = 'Ravi'; print(f'Hello, {name}') displays Hello, Ravi.
Q2:What is the difference between an f-string and string concatenation?
Answer:
String concatenation combines strings using operators such as +, sometimes requiring explicit conversion of non-string values. An f-string allows expressions to be embedded directly in readable text. For example, f'Age: {age}' is usually clearer than 'Age: ' + str(age).
Q3:How do you display a floating-point value with two decimal places?
Answer:
Use the .2f format specifier inside a replacement field. For example, price = 12.5; print(f'{price:.2f}') displays 12.50. This controls the displayed representation without changing the original variable.
Q4:How can you format a percentage with an f-string?
Answer:
Use the percent format specifier. For example, rate = 0.875; print(f'{rate:.1%}') displays 87.5%. Python multiplies the value by 100 for display and appends the percent sign.
Q5:How do you align text in a fixed-width field?
Answer:
Use a format specifier with a width and alignment character. For example, f'{name:<10}' left-aligns, f'{name:>10}' right-aligns, and f'{name:^10}' centers text in a field with a minimum width of ten characters.
Q6:How do you display literal curly braces in an f-string?
Answer:
Double the braces. Use {{ for a literal opening brace and }} for a literal closing brace. For example, print(f'{{value}}') displays {value}.
Q7:What is the difference between !s and !r in an f-string?
Answer:
!s applies str() to the value, while !r applies repr(). For message = 'hello', f'{message!s}' displays hello, whereas f'{message!r}' displays 'hello' with quotation marks. The representation is especially useful when debugging.
Q8:Do f-strings modify the variables they format?
Answer:
No. An f-string creates a string using the values of its expressions. Formatting a number with .2f does not overwrite the numeric variable or store a rounded value back into it.
Q9:What is the difference between the f prefix and the f in .2f?
Answer:
The f prefix immediately before the opening quote enables expression interpolation. The f in .2f is part of a numeric format specifier and requests fixed-point formatting with two digits after the decimal point.
Q10:What should you check when debugging an f-string?
Answer:
Check that the f prefix is present, replacement fields use balanced curly braces, expressions are valid, and format specifiers match the value's type. Then compare the actual output with the expected text, including spaces, decimal places, separators, and line breaks.

Key takeaways

  • An f-string begins with f or F before the opening quotation mark and allows expressions inside curly braces.
  • Python evaluates replacement-field expressions and inserts their formatted results into the string.
  • The .2f specifier displays two digits after the decimal point, while the comma option groups large numbers into thousands.
  • The percent format multiplies a value by 100 for display and appends a percent sign.
  • Width and alignment specifiers control padding and positioning; width does not automatically truncate long values.
  • Double curly braces display literal brace characters.
  • Formatting changes the displayed representation, not the original variable's stored value.
  • Trace examples carefully and verify exact output, including spaces and decimal places.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: