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
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
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
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
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
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
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
The comma in the format specifier groups the integer digits into thousands. The integer stored in population remains 1250000.
Note
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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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%.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is an f-string in Python?
Q2:What is the difference between an f-string and string concatenation?
Q3:How do you display a floating-point value with two decimal places?
Q4:How can you format a percentage with an f-string?
Q5:How do you align text in a fixed-width field?
Q6:How do you display literal curly braces in an f-string?
Q7:What is the difference between !s and !r in an f-string?
Q8:Do f-strings modify the variables they format?
Q9:What is the difference between the f prefix and the f in .2f?
Q10:What should you check when debugging an f-string?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: