Python F-Strings Basics Cheat Sheet
Python F-Strings Basics Cheat Sheet
rcent operator %
string.Template: template class of the string module Examples: Conversion Field
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
fill align sign #0 width sep .prec type # f-expressions need different quotes than the outer quotes
> - , 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'"
'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."
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 (*)
'Go ***center***'
# NOTE: the fill is the symbol (*), not the symbol as string ('*')
f"Go {'center':'*'^12}"
Example: Row Template for Table Creation Short List of Datetime Formatting Directives
import datetime
today = datetime.date.today()
f"{today}" '2022-03-14'