24. String interpolation
Note how we have to substitute name in twice? If we used variable names inside the substitution place holders, we only have to pass it in once. Also, note the use of f-string and Template.
24.1. Don’t do this
1name = 'John'
2food = 'pizza'
3sport = 'tennis'
4
5sentence = '{} likes to eat {}. {} likes to play {}.'.format(name, food, name, sport)
24.2. Do this
1name = 'John'
2food = 'pizza'
3sport = 'tennis'
4
5# variable substitution
6sentence = '{name} likes to eat {}. {name} likes to play {}.'.format(food, sport, name=name)
1name = 'John'
2food = 'pizza'
3sport = 'tennis'
4
5# f-string
6sentence = f'{name} likes to eat {food}. {name} likes to play {sport}.'
1from string import Template
2
3name = 'John'
4food = 'pizza'
5sport = 'tennis'
6
7# string template
8template = Template('$name likes to eat $food. $name likes to play $sport.')
9sentence = template.substitute(name=name, food=food, sport=sport)