Lesson 21:

String Formatting

You can typically combine strings with +.


In [1]:
'hello ' + 'world!'


Out[1]:
'helloworld!'

This gets harder with more variables.


In [4]:
name = 'Alice'
place = 'Main Street'
time = '6 pm'
food = 'turnips'

print('Hello ' + name + ', you are invited to a party at ' + place + ' at ' + time + '. Please bring ' + food + '.')


Hello Alice, you are invited to a party at Main Street at 6 pm. Please bring turnips.

Python has string interpolation, which uses %s to insert other strings into placeholders.


In [8]:
print(' Hello %s, you are invited to a party at %s at %s. Please bring %s.' % (name, place, time, food))


 Hello Alice, you are invited to a party at Main Street at 6 pm. Please bring turnips.