Python String Formatting
In this page:
F-Strings
F-strings remain the modern, recommended default for formatting in most code — this section goes a level deeper than the basics, focusing on nested expressions, computed field widths, and other capabilities of the format-spec mini-language that are easy to miss at first.
Example: F-Strings
name = "Alex"
value = 3.14159
width = 10
print(f"{name:{width}}|{value:.2f}")
The format() Method
Beyond the simple .format() calls covered earlier, the format-spec mini-language it shares with f-strings supports nested replacement fields, letting a width or precision itself come from a variable rather than being hardcoded in the template.
Example: The format() Method
value = 5
width = 8
print("{:{}}".format(value, width))
Percentage Formatting (%)
Percent-style (%) formatting predates both .format() and f-strings and is still occasionally seen in older codebases or logging configuration, so recognizing %s/%d/%f placeholders is useful even if you wouldn't choose that style for new code.
Example: Percentage Formatting (%)
name = "Alex"
age = 30
print("%s is %d years old" % (name, age))
Padding and Aligning
Combining alignment specifiers with computed widths — like f"{name:<{max_len}}" — lets you build console tables that stay aligned even when the data itself varies in length, rather than hardcoding a fixed column width.
Example: Padding and Aligning
names = ["Al", "Alexandra"]
max_len = max(len(n) for n in names)
for name in names:
print(f"{name:<{max_len}}|")
Formatting Decimals
The :.2f-style precision specifier isn't limited to two decimal places — the number before f can be any digit count, and combining it with a comma (:,.2f) adds thousands separators, both useful for formatting currency or large statistics cleanly.
Example: Formatting Decimals
amount = 1234567.891
print(f"{amount:,.2f}")
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: