Python String Formatting
Python String Formatting: F-Strings and Format Specifiers
Python string formatting lets you place variables, calculated values, and neatly formatted numbers inside a text template without clumsy concatenation. Since Python 3.6, f-strings (f"...") have been the clearest and usually the fastest way to do it, because you write expressions directly where they appear in the text. This lesson covers f-string format specifiers, the cases where .format() is still the better tool, and the mistakes that cause the most bugs.
How F-Strings Work
Put an f before the opening quote, and anything inside {} is evaluated as a Python expression and inserted into the string:
python
name = "Maya"
print(f"Hello, {name}!") # Hello, Maya!To control how a value looks, add a colon after the expression, followed by a format specifier. One short specifier can set decimal places, thousands separators, alignment, padding, or percentages.
Python String Formatting for Numbers, Percentages, and Alignment
The example below formats a price as currency, turns a ratio into a percentage, pads a column, and zero-pads an integer:
python
product = "SSD 1TB"
price = 1249.5
margin = 0.184
units = 7
print(f"{product:<12} | ${price:,.2f} | Margin: {margin:.1%}")
print(f"Batch #{units:04d}") # Batch #0007
The first line prints SSD 1TB | $1,249.50 | Margin: 18.4%.
Here is how each specifier reads:
<12left-aligns the text in a field 12 characters wide.,.2fAdds thousands separators and shows two decimal places..1%Multiplies by 100, shows one decimal place, and appends a percent sign.04dShows an integer padded with zeros to four digits.
When .format() Still Helps
F-strings evaluate immediately where you write them. If you load a reusable template string from a configuration file or translation table, store "Hello, {name}!" and call template.format(name=user) later.
Common Mistakes to Avoid
Using old
%formatting in new code:"%s: %d" % (a, b)fails awkwardly if you pass a tuple value and is harder to read than f-strings.Formatting untrusted user strings with
.format(): Never let users control the template passed to.format(), because format strings can inspect object attributes.Forgetting
{{and}}for literal braces: Inside an f-string, double curly braces{{and}}output literal{and}characters.
How to Check Your Formatting Works
Open a Python REPL ( do follow link hobe ) and run
python --versionto confirm you are on 3.6 or later (3.8+ for =, 3.12+ for reused quotes).Test the specifier on its own, such as
f"{1234.5:,.2f}". You should see1,234.50.Print the result inside delimiters, such as
print(f"[{value:>8}]"), so any extra spaces are visible.
Conclusion
F-strings should be your default for Python string formatting. They are readable, support compact format specifiers for numbers, percentages, and alignment, and handle debugging with=. Keep.format() For templates that are loaded or stored separately, avoid % in new code except for logging, and never pass untrusted input as a format template. With the specifiers in this lesson, most output formatting needs can be handled in a single line.
H2: Frequently Asked Questions (FAQs)
Are f-strings faster than + concatenation or .format()?
Generally, yes. CPython compiles f-strings into efficient bytecode, so they are usually faster than .format() and % formatting. Speed rarely matters for a few strings, so choose f-strings mainly for readability. If performance is critical, measure with the timeit module.
Can I put function calls or math inside {...}?
Yes. Any valid Python expression works, such as f"Total: {qty * unit_price:.2f}". For anything complex, calculate the value first.
What changed for f-strings in Python 3.12?
Python 3.12 lifted earlier parser limits. You can now use quotes matching the outer string, comments, and backslashes inside {...} expressions.
How do I print a literal curly brace in an f-string?
Double it: {{ prints { and }} prints }.
How do I format a number with thousands separators?
Use a comma or underscore in the specifier: f"{1234567:,}" gives 1,234,567.
Is .format() deprecated?
No. It is still supported and is the right choice when you create or store a template before the data is available.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.