Python F-Strings Basics Cheat Sheet
by Brian Allan (BrianAllan) via cheatography.com/133708/cs/29498/
What are F-Strings? Conversion Field Options
What are F-Strings? !s calls str() on the value of the f-expression
Strings prefixed with 'f' or 'F' and containing Python expressions !r calls repr() on the value of the f-expression
inside curly braces for evaluation at run time. They are more
!a calls ascii() on the value of the f-expression
formally known as "formatted string literals" and were introduced
with Python 3.6. str() returns string value representations that are human
readable for the end user.
How are F-Strings Useful?
repr() returns string value representations for the interpreter
They provide a concise, readable way to include the value of a and developers.
Python expression with formatting control inside strings. !s, !r, !a conversions are redundant since arbitrary expressions
What Are Other Ways to Format Strings in Python? are allowed in the replacement fields; so, one could just as easily
str.format(): the string format() method replace !r by using repr() on the f-expression and similarly for the
%-formatting: old string formatting using the string modulo/pe‐ others.
rcent operator %
string.Template: template class of the string module Examples: Conversion Field
x, name = 'cat', 'Sophia'
F-String Template # explicitly using the string conversion !s (the default)
f" text {replacement_field} text ... " f"The black {x!s}" 'The black cat'
Inside the quotes the f-string consists of two kinds of parts: (1) # using the string conversion !r adds quotes
regular string literals, i.e., text, and (2) replacement fields containing
f"The black {x!r}" "The black 'cat'"
Python expressions for evaluation along with formatting control.
f"Her name is {name!r}." "Her name is 'Sophia'."
Double quotes are used in this representative pattern but single
or triple quotes could also be used. # !r is equivalent to using repr() on the expression
F-strings may consist of just a replacement field: f"The black {repr(x)}" "The black 'cat'"
f"{replacement_field}"
Format Specifier
Replacement Field
{f-expression = !conversion:format_specifier} :fill align sign # 0 width sep .precision type
A replacement field is signaled by a pair of curly braces: { }
A replacement field consists of an expression with optional Brief Summary of the Format Specification Mini-Language
debugging mode (=), type conversion (!), and format specification fill : the padding character
(:). align : alignment of text within the space
Substituting into the f-string template: sign : how + and - are used preceding numbers
# : alternate presentation format for some number types
f" text {f-expression = !conversion:format_speci‐ 0 : sign-aware, zero-padding on numbers
fier} text ... " width : the minimum total field width
sep : the separator character for numbers (',' or '_')
.precision : determines how many digits displayed for floats;
maximum field width for strings
type : the type of presentation to use based on data type
Note: sign, #, 0, sep, precision, and type are of particular
interest for number formatting. For information about number format‐
ting, see my cheatsheet Python F-Strings Number Formatting.
By Brian Allan (BrianAllan) Published 16th March, 2022. Sponsored by Readable.com
cheatography.com/brianallan/ Last updated 15th March, 2022. Measure your website readability!
Page 1 of 4. https://readable.com
Python F-Strings Basics Cheat Sheet
by Brian Allan (BrianAllan) via cheatography.com/133708/cs/29498/
Format Specifier: Options Examples: Simple F-Strings (cont)
fill align sign #0 width sep .prec type # f-expressions need different quotes than the outer quotes
char < + digit(s) _ digit(s) string: s f'The black {'cat'}'
> - , number: n # Or, f-expressions can use a variable to represent the string
^ '' integer : d, b, o, f'The black {x}' 'The black cat'
x, X, c # for debugging, an equal sign can be used after an f-expression to
= float: e, E, f, F, display the expression text and its value
g, G, % f"The black {x=}" "The black x='cat'"
# backslash escapes can be used in text
String Presentation Type
f"The black \'cat\'" "The black 'cat'"
simplified form: f" text {f-expression:type} text ..."
# doubled curly braces for a single curly brace in text
s String format. This is the default type for strings and may be
f"The {{black}} {x}" 'The {black} cat'
omitted.
None Same as s # using .precision to enforce a maximum field width of 7
f"{'The black cat':.7}" 'The bla'
Where the value of the f-expression is a string, the replacement
field could make explicit the string presentation type {f-expres‐ # Multi-line f-strings
sion:s} but :s can be omitted since this is the default for strings. f"""
.precision can be used with strings to enforce a maximum field The black '\nThe black\ncat'
width: {f-expression:.precision} cat"""
Examples: Simple F-Strings Examples: Complex F-Expressions
x = 'cat' colors = ['blue', 'green', 'yellow', 'red']
# f-expression can be a string pets = {'cats': 2, 'dogs': 1}
f"The black {'cat'}" 'The black cat' # f-expression with indexing and a method call
# f-expression can be a variable with a string value f"{colors[2].title()} is my favorite color."
f"The black {x}" 'The black cat' 'Yellow is my favorite color.'
# error when neither a string nor a defined variable # f-expression with slicing
f"The black {cat}" f"{colors[:3]}"
# including f-string in string concatenation "['blue', 'green', 'yellow']"
'The ' 'black ' f"{x}" 'The black cat' # f-expression with a function call
# including f-string in string concatenation f"There are {len(colors)} options."
'The ' + 'black ' + f"{x}" 'The black cat' 'There are 4 options.'
# f-strings can use single, double, or triple quotes # using dictionary keys and an arithmetical operation
f'The ' f"black " f'''cat''' 'The black cat' f"She has {pets['cats'] + pets['dogs']} pets."
# text inside the f-string must contain a different kind of quotes than 'She has 3 pets.'
the outer quotes # for debugging, an equal sign can be used to display the f-expr‐
f'The 'black' cat' ession and its value
f"She has {pets['cats'] + pets['dogs'] = } pets."
"She has pets['cats'] + pets['dogs'] = 3 pets."
# using a conditional expression
By Brian Allan (BrianAllan) Published 16th March, 2022. Sponsored by Readable.com
cheatography.com/brianallan/ Last updated 15th March, 2022. Measure your website readability!
Page 2 of 4. https://readable.com
Python F-Strings Basics Cheat Sheet
by Brian Allan (BrianAllan) via cheatography.com/133708/cs/29498/
Examples: Complex F-Expressions (cont) Examples: Fill, Align, Width (cont)
f"She {'has' if (pets['cats'] > pets['dogs']) else # BUT: when using a nested replacement field for fill, the value of the
'does not have'} more cats than dogs." variable has to be the string of the symbol ('*'), not the symbol (*)
'She has more cats than dogs.' fill = '*'
f"Go {'center':{fill}^12}" 'Go ***center***'
# dictionary keys used by f-string must have different kind of quotes
f'She has {pet['cats']}.' # Default fill when not specified is the space character
f"Go {'right':>10}" 'Go right'
Formatting: Fill, Align, Width # Default for strings when not specified: fill (space), left align (<)
f"{f-expression:fill align width}" f"Go {'left':10}" 'Go left '
width a decimal integer defining the minimum total field width. If # Default for numbers when not specified: fill (space), right align (>)
not specified, the field width is determined by the content.
f"Total: {5:8}" 'Total: 5'
align determines the alignment of text within the available space --
left-aligned (<), right-aligned (>), or centered (^) Example: For Loop and Nested Replacement Fields
fill determines the character to use for padding to achieve the width = 12
minimum total field width. The default is the space character.
for text, fill in zip(['left', 'center', 'right'],
'<^>'):
Alignment Options
align = fill
< Left-alignment (the default for most objects) print(f"{text:{fill}{align}{width}}")
> Right-alignment (the default for numbers)
left<<<<<<<<
^ Centered ^^^center^^^
= Sign-aware padding. For numeric types: Places the padding >>>>>>>right
before the digits but after the sign (if any)
Example: Text Template Function
Examples: Fill, Align, Width # function with f-string as message template
# fill (.), right align (>), width (12) def message(name, num):
f"Go {'right':.>12}" 'Go .......right' return f"{name.title()}'s number is {num}."
message('jenny', 8675309)
# fill (!), left align (<), width (12)
f"Go {'left':!<12}" 'Go left!!!!!!!!' "Jenny's number is 8675309."
# 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}"
By Brian Allan (BrianAllan) Published 16th March, 2022. Sponsored by Readable.com
cheatography.com/brianallan/ Last updated 15th March, 2022. Measure your website readability!
Page 3 of 4. https://readable.com
Python F-Strings Basics Cheat Sheet
by Brian Allan (BrianAllan) via cheatography.com/133708/cs/29498/
Example: Row Template for Table Creation Short List of Datetime Formatting Directives
# data for table Directive Meaning Example
presidents = [ %A Weekday full name Sunday, Monday,...
['George Washington', 1, 1789, 1797],
%a Weekday abbreviated Sun, Mon,...
['John Adams', 2, 1797, 1801],
%B Month full name January, February,...
['Thomas Jefferson', 3, 1801, 1809]
] %b Month abbreviated Jan, Feb,...
# create row template function %d Day of Month 01, 02, 03,...
def row(name, num, start, end): %Y Year with Century 2019, 2020,...
return f"| {name:<20} | {num:2} | {start} -
%y Year without Century 19, 20,...
{end} |"
# print rows iteratively
References
for p in presidents:
"A Guide to the Newer Python String Format Techniques" by John
print(row(p[0], p[1], p[2], p[3]))
Sturtz at Real Python: https://realpython.com/python-formatted-ou‐
| George Washington | 1 | 1789 - 1797 | tput/#the-python-formatted-string-literal-f-string
| John Adams | 2 | 1797 - 1801 |
"Python 3's f-Strings: An Improved String Formatting Syntax
| Thomas Jefferson | 3 | 1801 - 1809 |
(Guide)" by Joanna Jablonski at Real Python: https://realpython.co‐
m/python-f-strings/
Example: Title Bar
"Format String Syntax" including "Format Specification Mini-Lang‐
fill, align, width = '*', '^', 21
uage" from the page "string -- Common string operations":
for text in ['', ' Title ', '']:
https://docs.python.org/3/library/string.html#format-string-syntax
print(f"{text:{fill}{align}{width}}")
"2.4.3. Formatted string literals" from the page "2. Lexical analys‐
********************* is": https://docs.python.org/3/reference/lexical_analysis.html#forma‐
******* Title ******* tted-string-literals
*********************
"PEP 498 -- Literal String Interpolation": https://www.python.org/d‐
ev/peps/pep-0498/
Datetime Formatting with F-Strings
"Python String Format Cookbook": https://mkaz.blog/code/pyth‐
Some Python objects have their own format specifiers to replace the on-string-format-cookbook/
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
import datetime
today = datetime.date.today()
f"{today}" '2022-03-14'
# object-specific formatting directives used in place of the standard
format specifiers
f"{today:%A, %B %d, %Y}"
'Monday, March 14, 2022'
# the output is the same as using the strftime() method of the
datetime module
today.strftime("%A, %B %d, %Y")
'Monday, March 14, 2022'
By Brian Allan (BrianAllan) Published 16th March, 2022. Sponsored by Readable.com
cheatography.com/brianallan/ Last updated 15th March, 2022. Measure your website readability!
Page 4 of 4. https://readable.com