F-strings in Python, introduced in Python 3.6, provide a concise and readable way to embed expressions directly within string literals. To create an f-string, prefix the string with f or F and use curly braces {} to include variables, expressions, or function calls.
Basic Syntax
name = "Alice"
age = 30
print(f"My name is {name} and I'm {age} years old.")Output: My name is Alice and I'm 30 years old.
Formatting Specifiers
Use a colon : inside the braces to apply formatting. Common format specifiers include:
:.2f→ Format float to 2 decimal placespi = 3.14159 print(f"Pi rounded to 2 decimals: {pi:.2f}") # Output: Pi rounded to 2 decimals: 3.14:05d→ Format integer with leading zeros to width 5num = 42 print(f"Zero-padded: {num:05d}") # Output: Zero-padded: 00042
Alignment and Padding
:<width>→ Left-align:>width→ Right-align:^width→ Center-align
text = "Python"
print(f"Left: '{text:<10}'") # Output: Left: 'Python '
print(f"Right: '{text:>10}'") # Output: Right: ' Python'
print(f"Center: '{text:^10}'") # Output: Center: ' Python 'Advanced Features
Self-documenting expressions (Python 3.8+): Use
=x = 10 print(f"{x=}") # Output: x=10Expression evaluation: Embed any valid Python expression
print(f"Sum: {2 + 3 * 4}") # Output: Sum: 14
Key Benefits
Faster than
%formatting and.format()More readable and maintainable
Supports any expression, including method calls and comprehensions
For full details, refer to the Python documentation on f-strings or the fstring.help cheat sheet.
To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:
"Hello %s" % name
yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do
"Hello %s" % (name,) # supply the single argument as a single-item tuple
which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.
Only use it for backwards compatibility with Python 2.5.
To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so the expression log.debug("some debug info: %s" % some_info) will first evaluate the string to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().
python - String formatting: % vs. .format vs. f-string literal - Stack Overflow
is there any difference between using string.format() or an fstring?
Why "f" strings?
That’s not useful. You use like so:
name = “Paul”
age = 12
print(f”{name} is {age} years old.”)
Purpose of the F-string
Videos
To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:
"Hello %s" % name
yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do
"Hello %s" % (name,) # supply the single argument as a single-item tuple
which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.
Only use it for backwards compatibility with Python 2.5.
To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so the expression log.debug("some debug info: %s" % some_info) will first evaluate the string to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().
Something that the modulo operator ( % ) can't do, afaik:
tu = (12,45,22222,103,6)
print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)
result
12 22222 45 22222 103 22222 6 22222
Very useful.
Another point: format(), being a function, can be used as an argument in other functions:
li = [12,45,78,784,2,69,1254,4785,984]
print map('the number is {}'.format,li)
print
from datetime import datetime,timedelta
once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
delta = timedelta(days=13, hours=8, minutes=20)
gen =(once_upon_a_time +x*delta for x in xrange(20))
print '\n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))
Results in:
['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']
2010-07-01 12:00:00
2010-07-14 20:20:00
2010-07-28 04:40:00
2010-08-10 13:00:00
2010-08-23 21:20:00
2010-09-06 05:40:00
2010-09-19 14:00:00
2010-10-02 22:20:00
2010-10-16 06:40:00
2010-10-29 15:00:00
2010-11-11 23:20:00
2010-11-25 07:40:00
2010-12-08 16:00:00
2010-12-22 00:20:00
2011-01-04 08:40:00
2011-01-17 17:00:00
2011-01-31 01:20:00
2011-02-13 09:40:00
2011-02-26 18:00:00
2011-03-12 02:20:00
Every time i see someone use format() instead of an fstring i get confused considering fstring has much more readability and is a lot more merciful on the programmer when there is more than 1 variable going into the string.