String formatting C-style,format and f-string

%

%s %f %d
string float integer

1 variable

1
'I buy %d bread' % 2

2 variables

1
'I buy %d bread and %d cake' % (2,3)

3 variables

1
'I buy %d bread ,%d cake and %d hats' % (2,3,4)

different variable type

1
'I buy %d bread and 3 %s' % (2,'cake')

how many digits

1
'1/6 is %f' % (1/6)


1
'1/6 is %.2f' % (1/6)

format

1 variable

1
'I buy {} bread'.format(2) 

2 variables

1
'I buy {} bread and {} cake'.format(2,3)

3 variables

1
'I buy {} bread ,{} cake and {} hats'.format(2,3,4)

different variable type

1
'I buy {} bread and 3 {}'.format(2,'cake')

how many digits

1
'1/6 is {}'.format(1/6)

1
'1/6 is {:.2f}'.format(1/6)

index

1
'I buy 1 {} and 3 {}'.format('cookie','cake')

or

1
2
3
x = 'cookie'
y = 'cake'
'I buy 1 {} and 3 {}'.format(x,y)


1
'I buy 1 {0} and 3 {0}'.format('cookie','cake')


1
'I buy 1 {1} and 3 {1}'.format('cookie','cake')


1
'I buy 1 {1} and 3 {0}'.format('cookie','cake')

f-string

1 variable

1
f'I buy {2} bread' 

or

1
2
number = 2
f'I buy {number} bread'

2 variables

1
f'I buy {2} bread and {3} cake'

3 variables

1
f'I buy {2} bread ,{3} cake and {4} hats'

different variable type

1
2
3
number = 2
item = 'cake'
f'I buy {2} bread and 3 {item}'

how many digits

1
f'1/6 is {1/6}'

1
f'1/6 is {1/6:.2f}'