python==3.8.5
Python - A collection of output formatting tips
python
Some handy Python output tips
About
This notebook is a collection of useful tips to format Python string literals and output.
Environment
f-string: Expressions inside a string
r = 'red'
g = 'green'
b = 1001
# f-string has a simple syntax. Put 'f' at the start of string, and put expressions in {}
f"Stop = {r}, Go = {g}"
'Stop = red, Go = green'
##
# 'F' can also be used to start an f-string
F"binary = {b}. If you need value in brackets {{{b}}}"
'binary = 1001. If you need value in brackets {1001}'
##
# functions can also be called from inside an f-string
f"This is in CAPS: { str.upper(r) }"
# same as above
f"This is in CAPS: { r.upper() }"
'This is in CAPS: RED'
f-string: Padding the output
##
# Inside f-string, passing an integer after ':' will cause that field to be a minimum number of characters wide.
# This is useful for making columns line up.
groups = {
'small': 100,
'medium': 100100,
'large': 100100100
}
for group, value in groups.items():
print(f"{value:10} ==> {group:20}")
print(f"{'****'*10}") # another nice trick
for group, value in groups.items():
print(f"{group:10} ==> {value:20}")
100 ==> small
100100 ==> medium
100100100 ==> large
****************************************
small ==> 100
medium ==> 100100
large ==> 100100100