• Home
  • 4.18 f-Strings – Part 2

4.18 f-Strings – Part 2

View Categories

4.18 f-Strings – Part 2

2 min read

In addition to inserting variables and expressions, f-strings support format specifications that control how values are displayed.

Using format specifiers, you can control the number of decimal places, alignment, field width, padding, percentages, and much more.

Format specifiers are written after a colon (:) inside the curly braces.

F-strings combine the simplicity of variable substitution with powerful formatting capabilities, making them the preferred choice for producing professional and readable output.


Syntax #

f"{expression:format_specifier}"

Components #

Component Description
f Indicates a formatted string literal.
{} Placeholder containing the value or expression.
: Separates the expression from the format specification.
format_specifier Controls how the value is displayed.

Example 1: Formatting Decimal Places #

main.py

price = 49.9876

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

Output #

Price: $49.99

Explanation #

  • {price:.2f} formats the floating-point number.
  • .2f displays exactly two digits after the decimal point.
  • Python rounds the value automatically.

Example 2: Displaying a Percentage #

main.py

marks = 0.92

print(f"Percentage: {marks:.0%}")

Output #

Percentage: 92%

Explanation #

  • % converts the decimal value into a percentage.
  • .0% displays no digits after the decimal point.
  • 0.92 becomes 92%.

Example 3: Right Alignment #

main.py

word = "Python"

print(f"|{word:>15}|")

Output #

|         Python|

Explanation #

  • > aligns the text to the right.
  • 15 specifies the total field width.
  • Extra spaces are added before the text.

Example 4: Left Alignment #

main.py

word = "Python"

print(f"|{word:<15}|")

Output #

|Python         |

Explanation #

  • < aligns the text to the left.
  • Spaces are added after the text.
  • The total width is 15 characters.

Example 5: Center Alignment #

main.py

title = "Menu"

print(f"|{title:^20}|")

Output #

|        Menu        |

Explanation #

  • ^ centers the text.
  • Spaces are added equally on both sides whenever possible.
  • The field width is 20 characters.

Example 6: Padding with Zeros #

main.py

number = 42

print(f"{number:05}")

Output #

00042

Explanation #

  • 5 specifies the total width.
  • Missing positions are filled with zeros.
  • The final output contains five characters.

Example 7: Thousands Separator #

main.py

population = 12345678

print(f"{population:,}")

Output #

12,345,678

Explanation #

  • , inserts commas as thousands separators.
  • Large numbers become easier to read.
  • The numeric value remains unchanged.

Example 8: Formatting Multiple Values #

main.py

name = "Alice"
score = 96.75

print(f"Student: {name}, Score: {score:.1f}")

Output #

Student: Alice, Score: 96.8

Explanation #

  • Multiple placeholders can appear in the same f-string.
  • The name is inserted directly.
  • The score is rounded to one decimal place.

Example 9: Evaluating Complex Expressions #

main.py

a = 8
b = 3

print(f"Average = {(a + b) / 2:.2f}")

Output #

Average = 5.50

Explanation #

  • The expression is evaluated first.
  • The result is then formatted using .2f.
  • Both calculation and formatting happen inside the f-string.

Example 10: Combining Alignment and Formatting #

main.py

item = "Book"
price = 15.5

print(f"|{item:<12}| ${price:>7.2f}")

Output #

|Book        | $  15.50

Explanation #

  • {item:<12} left-aligns the item name.
  • {price:>7.2f} right-aligns the price.
  • This style is commonly used when displaying tables and invoices.

Common Mistakes #

1. Forgetting the Colon Before the Format Specifier #

Incorrect

price = 49.95

print(f"{price.2f}")

Output #

SyntaxError: invalid decimal literal

Reason

The colon (:) separates the expression from the format specification.

Correct

print(f"{price:.2f}")

2. Using a Format Specifier on an Incompatible Type #

Incorrect

name = "Alice"

print(f"{name:.2f}")

Output #

ValueError: Unknown format code 'f' for object of type 'str'

Reason

.2f can only be used with numeric values.

Correct

print(f"{name}")

3. Forgetting the Field Width #

Incorrect

word = "Python"

print(f"|{word:>}|")

Output #

ValueError: Format specifier missing precision

Reason

Alignment symbols should normally be followed by a field width.

Correct

print(f"|{word:>10}|")

4. Expecting Formatting to Change the Original Variable #

Incorrect

price = 49.9876

print(f"{price:.2f}")
print(price)

Incorrect Expectation #

49.99
49.99

Actual Output #

49.99
49.9876

Reason

Formatting only changes how the value is displayed.
The original variable remains unchanged.


Best Practices #

  • Use f-strings for all new Python programs.
  • Apply format specifiers to improve readability.
  • Use .2f for displaying floating-point values such as prices or measurements.
  • Use alignment specifiers when printing tables or reports.
  • Keep expressions inside f-strings simple and readable.

Key Points to Remember #

  • Format specifiers are written after a colon (:) inside {}.
  • .2f displays two decimal places.
  • % converts a decimal value to a percentage.
  • <, >, and ^ control left, right, and center alignment.
  • Commas (,) add thousands separators.
  • Formatting changes only the displayed output, not the original variable.
  • F-strings are the recommended formatting method in modern Python.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *