Python - A collection of output formatting tips

python
Some handy Python output tips
Published

February 18, 2022

About

This notebook is a collection of useful tips to format Python string literals and output.

Environment

Code
from platform import python_version

print("python==" + python_version())
python==3.8.5

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}'
##
# f-string can also be started with """ quotes
f"""{r} or {g}"""
'red or green'
##
# f-string on multiple lines. 
# 1. Use """ with backslash \
f"""{r}\
 or \
{g}"""
'red or green'
##
# f-string on multiple lines. 
# 2. Use only backslash \
f"{r}" \
" or " \
f"{g}"
'red or green'
##
# f-string on multiple lines. 
# 3. Use  brackets ()
(f"{r}"
" or "
f"{g}")
'red or green'
##
# you can also compute an expression in an f-string
f"{ 40 + 2}"
'42'
##
# 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

f-string: Binary and hexadecimal format

##
# you can convert integers to binary and hexadecimal format
print( f"5 in binary {5:b}" )

print( f"5 in hexadecimal {5:#b}" )
5 in binary 101
5 in hexadecimal 0b101

f-string: Controlling the decimal places

import math
print(f'The value of pi is approximately (no formatting) {math.pi}')
print(f'The value of pi is approximately {math.pi :.3f}')
The value of pi is approximately (no formatting) 3.141592653589793
The value of pi is approximately 3.142

f-string: Putting commas in numerical output

num = 3214298342.234
f"{num:,}"
'3,214,298,342.234'