String formating - AndrewMZ6/python_cheat_sheet GitHub Wiki

f - string

f-strings were implemented in Python 3.6 which was released Dec.23, 2016. Documentation about the feature is written in PEP498

def func(*a, **s):

	args_response = f'args = {a}, type of args = {type(a).__name__}, length of args = { len(a) } '
	print(args_response)

	print(f'kwargs = {s}, type of kwargs = {type(s).__name__} length of kwargs = {len(s)}')

func(1, [1, 2, 3], key1 = 31, key2 = 'strawberrys')

Output:

args = (1, [1, 2, 3]), type of args = tuple, length of args = 2 
kwargs = {'key1': 31, 'key2': 'strawberrys'}, type of kwargs = dict length of kwargs = 2

str.format()

We can use format method to insert values instead of {} brackets

>>> '{} darkness my old {}'.format('Hello', 'friend')
'Hello darkness my old friend'

When using formating like this Python automatically assumes that value 'Hello' should be pasted first since it's first in order.
We can write order explicitly by numerating brackets

>>> '{1} darkness my old {0}'.format('Hello', 'friend')
'friend darkness my old Hello'

C like %s formating

>>> '%s darkness my old %s' % ('Hello', 'friend')
'Hello darkness my old friend'

The number of %s operators MUST be equal to number of elements in tuple argument