Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
93 views

Python F-Strings Basics Cheat Sheet

F-strings provide a concise way to include Python expressions in strings. An f-string contains text and replacement fields that are evaluated at runtime. Replacement fields can include expressions, conversion flags, and format specifiers to control formatting of values.

Uploaded by

Silga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Python F-Strings Basics Cheat Sheet

F-strings provide a concise way to include Python expressions in strings. An f-string contains text and replacement fields that are evaluated at runtime. Replacement fields can include expressions, conversion flags, and format specifiers to control formatting of values.

Uploaded by

Silga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

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-expr​ession


Strings prefixed with 'f' or 'F' and containing Python expres​​sions !r calls repr() on the value of the f-expr​ession
inside curly braces for evaluation at run time. They are more
!a calls ascii() on the value of the f-expr​ession
formally known as "​for​matted string litera​ls" and were introduced
with Python 3.6.  str() returns string value repres​ent​ations that are human
readable for the end user.
How are F-Strings Useful?
 repr() returns string value repres​ent​ations for the interp​reter
They provide a concise, readable way to include the value of a and develo​pers.
Python expres​​sion with formatting control inside strings.  !s, !r, !a conver​sions are redundant since arbitrary expres​sions
What Are Other Ways to Format Strings in Python? are allowed in the replac​ement fields; so, one could just as easily
 str.fo​rmat(): the string format() method replace !r by using repr() on the f-expr​ession and similarly for the

 %-form​atting: old string formatting using the string modulo​/pe​‐ others.

rcent operator %
 string.Te​mplate: 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) replac​ement fields containing
f"The black {x!r}" "The black 'cat'"
Python expres​sions for evaluation along with formatting control.
f"Her name is {name!​r}."​ "Her name is 'Sophi​a'."​
 Double quotes are used in this repres​ent​ative 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 replac​ement field: f"The black {repr(​x)}​" "The black 'cat'"
f"{r​epl​ace​men​t_f​iel​d}"
Format Specifier
Replac​ement Field

{f-expression = !conversion:format_specifier} :fill align sign # 0 width sep .precision type


 A replac​ement field is signaled by a pair of curly braces: { }
 A replac​ement field consists of an expression with optional Brief Summary of the Format Specif​ication Mini-L​anguage
debugging mode (=), type conversion (!), and format specif​ication fill : the padding character

(:). align : alignment of text within the space

 Substi​tuting into the f-string template: sign : how + and - are used preceding numbers
# : alternate presen​tation format for some number types
f" text {f-exp​ression = !conve​rsi​on:​for​mat​_sp​eci​‐ 0 : sign-a​ware, zero-p​adding 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 presen​tation to use based on data type

Note: sign, #, 0, sep, precision, and type are of particular


interest for number formatting. For inform​ation 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-expr​essions need different quotes than the outer quotes

char < + digit(s) _ digit(s) string: s f'The black {'cat'}' 

> - , number: n # Or, f-expr​essions 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-expr​ession 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 Presen​tation Type
f"The black \'cat​\'" "The black 'cat'"
simplified form: f" text {f-exp​res​sio​n: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-expr​ession is a string, the replac​ement
field could make explicit the string presen​tation type {f-exp​res​‐ # 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-exp​res​sio​n:.p​re​cision} cat"​"​"

Examples: Simple F-Strings Examples: Complex F-Expr​essions

x = 'cat' colors = ['blue', 'green', 'yellow', 'red']

# f-expr​ession can be a string pets = {'cats': 2, 'dogs': 1}


f"The black {'cat'​}" 'The black cat' # f-expr​ession with indexing and a method call
# f-expr​ession can be a variable with a string value f"{c​olo​rs[​2].t​it​le()} 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-expr​ession with slicing
f"The black {cat}"  f"{c​olo​rs[​:3]​}"

# including f-string in string concat​enation "['blue', 'green', 'yello​w']​"


'The ' 'black ' f"{x​}" 'The black cat' # f-expr​ession with a function call

# including f-string in string concat​enation f"There are {len(c​olors)} option​s."

'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 arithm​etical 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 condit​ional 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-Expr​essions (cont) Examples: Fill, Align, Width (cont)

f"She {'has' if (pets[​'cats'] > pets['​dogs']) else # BUT: when using a nested replac​ement 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 {'cent​er'​:{f​ill​}^1​2}" 'Go ***cen​ter***'
# dictionary keys used by f-string must have different kind of quotes
f'She has {pet['​cat​s']}.'  # Default fill when not specified is the space character
f"Go {'righ​t':​>10​}" 'Go ​ ​ ​ ​ ​ ​right'
Format​ting: Fill, Align, Width # Default for strings when not specified: fill (space), left align (<)
f"{f​-ex​pre​ssi​on:fill align width}​" f"Go {'left​':1​0}" '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-a​ligned (<), right-​aligned (>), or centered (^) Example: For Loop and Nested Replac​ement 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-a​lig​nment (the default for most objects) ​ ​ ​ ​pri​nt(​f"{t​ext​:{f​ill​}{a​lig​n}{​wid​th}​}")
> Right-​ali​gnment (the default for numbers)
left<<<<<<<<
^ Centered ^^^cen​ter^^^
= 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 messag​e(name, num):

f"Go {'righ​t':.>1​2}" 'Go .......right' ​ ​ ​ ​return f"{n​ame.ti​tle​()}'s number is {num}."​


messag​e('​jenny', 8675309)
# fill (!), left align (<), width (12)

f"Go {'left​':!​<12​}" 'Go left!!​!!!!!!' "Jenny's number is 867530​9."

# fill (*), center align (^), width (12)


f"Go {'cent​er'​:*^​12}​" 'Go ***cen​ter***'

# nested replac​ement fields allow for the use of variables in the


format specifier
fill, align, width = '*', '^', 12
f"Go {'cent​er'​:{f​ill​}{a​lig​n}{​wid​th}​}"

'Go ***cen​ter***'
# NOTE: the fill is the symbol (*), not the symbol as string ('*')
f"Go {'cent​er'​:'*​'^1​2}" 

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,...
​ ​ ​ ​['G​eorge Washin​gton', 1, 1789, 1797],
%a Weekday abbrev​iated Sun, Mon,...
​ ​ ​ ​['John Adams', 2, 1797, 1801],
%B Month full name January, Februa​ry,...
​ ​ ​ ​['T​homas Jeffer​son', 3, 1801, 1809]
] %b Month abbrev​iated 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 iterat​ively
References
for p in presid​ents:
 "A Guide to the Newer Python String Format Techni​que​s" by John
​ ​ ​ ​pri​nt(​row​(p[0], p[1], p[2], p[3]))
Sturtz at Real Python: https:​//r​eal​pyt​hon.co​m/p​yth​on-​for​mat​ted​-ou​‐
| George Washington | 1 | 1789 - 1797 | tpu​t/#​the​-py​tho​n-f​orm​att​ed-​str​ing​-li​ter​al-​f-s​tring
| 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:​//r​eal​pyt​hon.co​‐
m/p​yth​on-​f-s​trings/
Example: Title Bar
 "​Format String Syntax​" including "​Format Specif​ication Mini-L​ang​‐
fill, align, width = '*', '^', 21
uag​e" from the page "string -- Common string operat​ion​s":
for text in ['', ' Title ', '']:
https:​//d​ocs.py​tho​n.o​rg/​3/l​ibr​ary​/st​rin​g.h​tml​#fo​rma​t-s​tri​ng-​syntax
​ ​ ​ ​pri​nt(​f"{t​ext​:{f​ill​}{a​lig​n}{​wid​th}​}")
 "​2.4.3. Formatted string litera​ls" from the page "2. Lexical analys​‐
********************* is": https:​//d​ocs.py​tho​n.o​rg/​3/r​efe​ren​ce/​lex​ica​l_a​nal​ysi​s.h​tml​#fo​rma​‐
******* Title ******* tte​d-s​tri​ng-​lit​erals
*******​***​***​***​*****
 "PEP 498 -- Literal String Interp​ola​tio​n": https:​//w​ww.p​yt​hon.or​g/d​‐
ev/​pep​s/p​ep-​0498/
Datetime Formatting with F-Strings
 "​Python String Format Cookbo​ok": https:​//m​kaz.bl​og/​cod​e/p​yth​‐
Some Python objects have their own format specifiers to replace the on-​str​ing​-fo​rma​t-c​ook​book/
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 = dateti​me.d​at​e.t​oday()
f"{t​oda​y}" '2022-03-14'

# object​-sp​ecific formatting directives used in place of the standard


format specifiers
f"{t​oda​y:%A, %B %d, %Y}"

'Monday, March 14, 2022'


# the output is the same as using the strftime() method of the
datetime module

today.s​tr​fti​me(​"%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

You might also like