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 inside {} and substitute them with the variables values 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:
- PEP 498 Literal String Interpolation
- Python String Formatting
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
PEP 498 introduced a
new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings [because of the leading f character preceding the string literal]. The idea behind f-strings is to make string interpolation simpler.
To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with
str.format[]. F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.
Code #1 :
Python3
val
=
'Geeks'
print
[f
"{val}for{val} is a portal for {val}."
]
name
=
'Tushar'
age
=
23
print
[f
"Hello, My name is {name} and I'm {age} years old."
]
Output :
GeeksforGeeks is a portal for Geeks. Hello, My name is Tushar and I'm 23 years old.
Code #2 :
Python3
import
datetime
today
=
datetime.datetime.today[]
print
[f
"{today:%B %d, %Y}"
]
Output :
April 04, 2018
Note : F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and
str.format[].
Let’s see few error examples, which might occur while using f-string :
Code #3 : Demonstrating Syntax error.
Python3
answer
=
456
f
"Your answer is "
{answer}""
Code #4 : Backslash Cannot be used in format string directly.
Python3
Output :
Traceback [most recent call last]: Python Shell, prompt 29, line 1 Syntax Error: f-string expression part cannot include a backslash: , line 1, pos 0
But
the documentation points out that we can put the backslash into a variable as a workaround though :
Python3
newline
=
ord
[
'\n'
]
print
[f
"newline: {newline}"
]
Output :
newline: 10
Reference : PEP 498, Literal String
Interpolation