In Python 3.6, the f-string, formatted string literal, was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast.
Example:
agent_name = 'James Bond'
kill_count = 9
# old ways
print("%s has killed %d enemies" % (agent_name,kill_count))
print('{} has killed {} enemies'.format(agent_name,kill_count))
print('{name} has killed {kill} enemies'.format(name=agent_name,kill=kill_count))
# f-strings way
print(f'{agent_name} has killed {kill_count} enemies')
The f
or F
in front of strings tell Python to look at the values , expressions or instance inside {} and substitute them with the variables values or results if exists. The best thing about f-formatting is that you can do cool stuff in {}, e.g. {kill_count * 100}
.
You can use it to debug using print e.g.
print(f'the {agent_name=}.')
# the agent_name='James Bond'
Formatting, such as zero-padding, float and percentage rounding is made easier:
print(f'{agent_name} shoot with {9/11 : .2f} or {9/11: .1%} accuracy')
# James Bond shoot with 0.82 or 81.8% accuracy
Even cooler is the ability to nest and format. Example date
from datetime import datetime
lookup = {
'01': 'st',
'21': 'st',
'31': 'st',
'02': 'nd',
'22': 'nd',
'03': 'rd',
'23': 'rd'
}
print(f"{datetime.now(): %B %d{lookup.get('%B', 'th')} %Y}")
# April 14th 2022
Pretty formatting is also easier
tax = 1234
print(f'{tax:,}') # separate 1k \w comma
# 1,234
print(f'{tax:,.2f}') # all two decimals
# 1,234.00
print(f'{tax:~>8}') # pad left with ~ to fill eight characters or < other direction
# ~~~~1234
print(f'{tax:~^20}') # centre and pad
# ~~~~~~~~1234~~~~~~~~
The __format__
allows you to funk with this feature. Example
class Money:
def __init__(self, currency='€'):
self.currency = currency
def __format__(self, value):
return f"{self.currency} {float(value):.2f}"
tax = 12.34
money = Money(currency='$')
print(f'{money: {tax}}')
# $ 12.34
There is much more. Readings: