Contains formulas, tables, and examples showing patterns and options, with the exception of number formatting, for Python's Formatted String Literals -- i.e., F-Strings.
|
What are F-Strings?
Strings prefixed with 'f' or 'F' and containing Python expressions inside curly braces for evaluation at run time. They are more formally known as "formatted string literals" and were introduced with Python 3.6.
|
|
How are F-Strings Useful?
They provide a concise, readable way to include the value of a Python expression with formatting control inside strings.
|
|
What Are Other Ways to Format Strings in Python?
{{lang-py}}str.format(): the string {{lang-py}}format() method %-formatting: old string formatting using the string modulo/percent operator % {{lang-py}}string.Template: template class of the string module
|
**f" *text* {replacement_field} *text* ... "**
{{lang-py}}f"{replacement_field}"
**{f-expression = !conversion:format_specifier}**
{ }=), type conversion (!), and format specification (:).
!s |
calls
str() on the value of the f-expression |
||
!r |
calls
repr() on the value of the f-expression |
||
!a |
calls
ascii() on the value of the f-expression |
||
str() returns string value representations that are human readable for the end user.repr() returns string value representations for the interpreter and developers.!s, !r, !a conversions are redundant since arbitrary expressions are allowed in the replacement fields; so, one could just as easily replace !r by using repr() on the f-expression and similarly for the others.
x, name = 'cat', 'Sophia' |
|
|
# explicitly using the string conversion
!s (the default) |
|
f"The black {x!s}" |
'The black cat'
|
|
# using the string conversion
!r adds quotes |
|
f"The black {x!r}" |
"The black 'cat'"
|
f"Her name is {name!r}." |
"Her name is 'Sophia'."
|
|
#
!r is equivalent to using repr() on the expression |
|
f"The black {repr(x)}" |
"The black 'cat'"
|
:fill align sign # 0 width sep .precision type fill : the padding character align : alignment of text within the space sign : how + and - are used preceding numbers # : alternate presentation format for some number types 0 : sign-aware, zero-padding on numbers width : the minimum total field width sep : the separator character for numbers (',' or '_').precision : determines how many digits displayed for floats;type : the type of presentation to use based on data typesign, #, 0, sep, precision, and type are of particular interest for number formatting. For information about number formatting, see my cheatsheet Python F-Strings Number Formatting.
|
fill
|
align
|
sign
|
#
0 |
width
|
sep
|
.prec
|
type
|
|
char
|
<
|
+
|
digit(s)
|
_
|
digit(s)
|
string: s
|
|
|
>
|
-
|
,
|
number: n
|
||||
|
^
|
' '
|
integer: d, b, o, x, X, c
|
|||||
|
=
|
float: e, E, f, F, g, G, %
|
|
simplified form:
f" text {f-expression:type} text ..." |
|
s |
String format. This is the default type for strings and may be omitted.
|
|
None
|
Same as
s |
{f-expression:s} but :s can be omitted since this is the default for strings..precision can be used with strings to enforce a maximum field width: {f-expression:.precision}
x = 'cat' |
|
|
# f-expression can be a string
|
|
f"The black {'cat'}" |
'The black cat'
|
|
# f-expression can be a variable with a string value
|
|
f"The black {x}" |
'The black cat'
|
|
# error when neither a string nor a defined variable
|
|
f"The black {cat}" |
|
|
# including f-string in string concatenation
|
|
'The ' 'black ' f"{x}" |
'The black cat'
|
|
# including f-string in string concatenation
|
|
'The ' + 'black ' + f"{x}" |
'The black cat'
|
|
# f-strings can use single, double, or triple quotes
|
|
f'The ' f"black " f'''cat''' |
'The black cat'
|
|
# text inside the f-string must contain a different kind of quotes than the outer quotes
|
|
f'The 'black' cat' |
|
|
# f-expressions need different quotes than the outer quotes
|
|
f'The black {'cat'}' |
|
|
# Or, f-expressions can use a variable to represent the string
|
|
f'The black {x}' |
'The black cat'
|
|
# for debugging, an equal sign can be used after an f-expression to display the expression text and its value
|
|
f"The black {x=}" |
"The black x='cat'"
|
|
# backslash escapes can be used in text
|
|
f"The black \'cat\'" |
"The black 'cat'"
|
|
# doubled curly braces for a single curly brace in text
|
|
f"The {{black}} {x}" |
'The {black} cat'
|
|
# using .precision to enforce a maximum field width of 7
|
|
f"{'The black cat':.7}" |
'The bla'
|
|
# Multi-line f-strings
|
|
f"""The black cat""" |
'\nThe black\ncat' |
colors = ['blue', 'green', 'yellow', 'red'] |
|
pets = {'cats': 2, 'dogs': 1} |
|
|
# f-expression with indexing and a method call
|
|
f"{colors[2].title()} is my favorite color." |
|
|
'Yellow is my favorite color.'
|
|
|
# f-expression with slicing
|
|
f"{colors[:3]}" |
|
|
"['blue', 'green', 'yellow']"
|
|
|
# f-expression with a function call
|
|
f"There are {len(colors)} options." |
|
|
'There are 4 options.'
|
|
|
# using dictionary keys and an arithmetical operation
|
|
f"She has {pets['cats'] + pets['dogs']} pets." |
|
|
'She has 3 pets.'
|
|
|
# for debugging, an equal sign can be used to display the f-expression and its value
|
|
f"She has {pets['cats'] + pets['dogs'] = } pets." |
|
|
"She has pets['cats'] + pets['dogs'] = 3 pets."
|
|
|
# using a conditional expression
|
|
f"She {'has' if (pets['cats'] > pets['dogs']) else 'does not have'} more cats than dogs." |
|
|
'She has more cats than dogs.'
|
|
|
# dictionary keys used by f-string must have different kind of quotes
|
|
f'She has {pet['cats']}.' |
|
f"{f-expression:fill align width}" |
|
|
width
|
a decimal integer defining the minimum total field width. If not specified, the field width is determined by the content.
|
|
align
|
determines the alignment of text within the available space -- left-aligned (<), right-aligned (>), or centered (^)
|
|
fill
|
determines the character to use for padding to achieve the minimum total field width. The default is the space character.
|
|
<
|
Left-alignment (the default for most objects)
|
|
>
|
Right-alignment (the default for numbers)
|
|
^
|
Centered
|
|
=
|
Sign-aware padding. For numeric types: Places the padding before the digits but after the sign (if any)
|
|
# fill (.), right align (>), width (12)
|
|
f"Go {'right':.>12}" |
'Go .......right'
|
|
# fill (!), left align (<), width (12)
|
|
f"Go {'left':!<12}" |
'Go left!!!!!!!!'
|
|
# fill (*), center align (^), width (12)
|
|
f"Go {'center':*^12}" |
'Go ***center***'
|
|
# nested replacement fields allow for the use of variables in the format specifier
|
|
fill, align, width = '*', '^', 12 f"Go {'center':{fill}{align}{width}}" |
|
|
'Go ***center***'
|
|
|
# NOTE: the fill is the symbol (*), not the symbol as string ('*')
|
|
f"Go {'center':'*'^12}" |
|
|
# BUT: when using a nested replacement field for fill, the value of the variable has to be the string of the symbol ('*'), not the symbol (*)
|
|
fill = '*' f"Go {'center':{fill}^12}" |
'Go ***center***' |
|
# Default fill when not specified is the space character
|
|
f"Go {'right':>10}" |
'Go right'
|
|
# Default for strings when not specified: fill (space), left align (<)
|
|
f"Go {'left':10}" |
'Go left '
|
|
# Default for numbers when not specified: fill (space), right align (>)
|
|
f"Total: {5:8}" |
'Total: 5'
|
width = 12
for text, fill in zip(['left', 'center', 'right'], '<^>'):
align = fill
print(f"{text:{fill}{align}{width}}")
# function with f-string as message template
def message(name, num):
return f"{name.title()}'s number is {num}."
message('jenny', 8675309)
# data for table
presidents = [
['George Washington', 1, 1789, 1797],
['John Adams', 2, 1797, 1801],
['Thomas Jefferson', 3, 1801, 1809]
]
# create row template function
def row(name, num, start, end):
return f"| {name:<20} | {num:2} | {start} - {end} |"
# print rows iteratively
for p in presidents:
print(row(p[0], p[1], p[2], p[3]))
{{lang-py}}fill, align, width = '*', '^', 21
for text in ['', ' Title ', '']:
print(f"{text:{fill}{align}{width}}")
|
Some Python objects have their own format specifiers to replace the standard ones. An example of this behavior is found in the
date, datetime, and time objects of the datetime module. |
|
|
# using the
datetime module to obtain today's date |
|
{{lang-py}}import datetime{{lang-py}}today = datetime.date.today(){{lang-py}}f"{today}" |
'2022-03-14' |
|
# object-specific formatting directives used in place of the standard format specifiers
|
|
{{lang-py}}f"{today:%A, %B %d, %Y}" |
|
|
'Monday, March 14, 2022'
|
|
|
# the output is the same as using the
strftime() method of the datetime module |
|
{{lang-py}}today.strftime("%A, %B %d, %Y") |
|
|
'Monday, March 14, 2022'
|
|
|
Directive
|
Meaning
|
Example
|
%A |
Weekday full name
|
Sunday, Monday,...
|
%a |
Weekday abbreviated
|
Sun, Mon,...
|
%B |
Month full name
|
January, February,...
|
%b |
Month abbreviated
|
Jan, Feb,...
|
%d |
Day of Month
|
01, 02, 03,...
|
%Y |
Year with Century
|
2019, 2020,...
|
%y |
Year without Century
|
19, 20,...
|
|
"A Guide to the Newer Python String Format Techniques" by John Sturtz at Real Python: https://realpython.com/python-formatted-output/#the-python-formatted-string-literal-f-string
|
|
"Python 3's f-Strings: An Improved String Formatting Syntax (Guide)" by Joanna Jablonski at Real Python: https://realpython.com/python-f-strings/
|
|
"Format String Syntax" including "Format Specification Mini-Language" from the page "
string -- Common string operations": https://docs.python.org/3/library/string.html#format-string-syntax |
|
"2.4.3. Formatted string literals" from the page "2. Lexical analysis": https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals
|
|
"PEP 498 -- Literal String Interpolation": https://www.python.org/dev/peps/pep-0498/
|
|
"Python String Format Cookbook": https://mkaz.blog/code/python-string-format-cookbook/
|
Thanks for taking the time to compile this! I've been searching for a suitable reference on f-strings and not really finding much.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.