What are 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? str.format()
: the string format()
method %-formatting: old string formatting using the string modulo/percent operator % string.Template
: template class of the string module
|
F-String Template
f" text {replacement_field} text ... "
|
Inside the quotes the f-string consists of two kinds of parts: (1) regular string literals, i.e., text, and (2) replacement fields containing Python expressions for evaluation along with formatting control.
Double quotes are used in this representative pattern but single or triple quotes could also be used.
F-strings may consist of just a replacement field:
f"{replacement_field}"
Replacement Field
{f-expression = !conversion:format_specifier}
|
A replacement field is signaled by a pair of curly braces: { }
A replacement field consists of an expression with optional debugging mode ( =
), type conversion ( !
), and format specification ( :
).
Substituting into the f-string template:
f" text {f-expression = !conversion:format_specifier} text ... "
Conversion Field Options
|
calls str()
on the value of the f-expression |
|
calls repr()
on the value of the f-expression |
|
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.
Examples: Conversion Field
x, name = 'cat', 'Sophia'
|
# explicitly using the string conversion !s
(the default) |
|
'The black cat' |
# using the string conversion !r
adds quotes |
|
"The black 'cat'" |
f"Her name is {name!r}."
|
"Her name is 'Sophia'." |
# !r
is equivalent to using repr()
on the expression |
|
"The black 'cat'" |
Format Specifier
:fill align sign # 0 width sep .precision type
Brief Summary of the Format Specification Mini-Language
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; 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 formatting, see my cheatsheet Python F-Strings Number Formatting.
Format Specifier: Options
fill |
align |
sign |
|
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, % |
String Presentation Type
simplified form: f" text {f-expression:type} text ..."
|
|
String format. This is the default type for strings and may be omitted. |
None |
|
Where the value of the f-expression is a string, the replacement field could make explicit the string presentation type {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}
Examples: Simple F-Strings
|
# f-expression can be a string |
|
'The black cat' |
# f-expression can be a variable with a string value |
|
'The black cat' |
# error when neither a string nor a defined variable |
|
|
# including f-string in string concatenation |
|
'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-expressions need different quotes than the outer quotes |
|
|
# Or, f-expressions can use a variable to represent the string |
|
'The black cat' |
# for debugging, an equal sign can be used after an f-expression to display the expression text and its value |
|
"The black x='cat'" |
# backslash escapes can be used in text |
|
"The black 'cat'" |
# doubled curly braces for a single curly brace in text |
|
'The {black} cat' |
# using .precision to enforce a maximum field width of 7 |
|
'The bla' |
# Multi-line f-strings |
|
'\nThe black\ncat'
|
|
|
Examples: Complex F-Expressions
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 |
|
"['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']}.'
|
|
Formatting: Fill, Align, Width
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. |
Alignment Options
< |
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) |
Examples: Fill, Align, Width
# fill (.), right align (>), width (12) |
|
'Go .......right' |
# fill (!), left align (<), width (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 |
|
'Go right' |
# Default for strings when not specified: fill (space), left align (<) |
|
'Go left ' |
# Default for numbers when not specified: fill (space), right align (>) |
|
'Total: 5' |
Example: For Loop and Nested Replacement Fields
width = 12
for text, fill in zip(['left', 'center', 'right'], '<^>'):
align = fill
print(f"{text:{fill}{align}{width}}")
|
left<<<<<<<<
^^^center^^^
>>>>>>>right
Example: Text Template Function
# function with f-string as message template
def message(name, num):
return f"{name.title()}'s number is {num}."
message('jenny', 8675309)
|
"Jenny's number is 8675309."
Example: Row Template for Table Creation
# 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]))
|
| George Washington | 1 | 1789 - 1797 |
| John Adams | 2 | 1797 - 1801 |
| Thomas Jefferson | 3 | 1801 - 1809 |
Example: Title Bar
fill, align, width = '*', '^', 21
for text in ['', ' Title ', '']:
print(f"{text:{fill}{align}{width}}")
|
*********************
******* Title *******
*********************
Datetime Formatting with F-Strings
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 |
import datetime today = datetime.date.today() f"{today}"
|
'2022-03-14'
|
# object-specific formatting directives used in place of the standard format specifiers |
|
'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' |
Short List of Datetime Formatting Directives
Directive |
Meaning |
Example |
|
Weekday full name |
Sunday, Monday,... |
|
Weekday abbreviated |
Sun, Mon,... |
|
Month full name |
January, February,... |
|
Month abbreviated |
Jan, Feb,... |
|
Day of Month |
01, 02, 03,... |
|
Year with Century |
2019, 2020,... |
|
Year without Century |
19, 20,... |
|
Created By
Metadata
Comments
Charlie Dimaggio, 08:33 26 Apr 22
Thanks for taking the time to compile this! I've been searching for a suitable reference on f-strings and not really finding much.
Add a Comment
Related Cheat Sheets
More Cheat Sheets by BrianAllan