Game Development Reference
In-Depth Information
11 - Bagels
>>> name = 'Alice'
>>> event = 'party'
>>> where = 'the pool'
>>> when = 'Saturday'
>>> time = '6:00pm'
>>> print('Hello, ' + name + '. Will you go to the
' + event + ' at ' + where + ' this ' + when + '
at ' + time + '?')
Hello, Alice. Will you go to the party at the pool
this Saturday at 6:00pm?
>>>
As you can see, it can be very hard to type a line that concatenates several strings
together. Instead, you can use string interpolation , which lets you put placeholders like
%s (these placeholders are called conversion specifiers ), and then put all the variable
names at the end. Each %s is replaced with the value in the variable at the end of the line.
For example, the following code does the same thing as the above code:
name = 'Alice'
event = 'party'
where = 'the pool'
when = 'Saturday'
time = '6:00pm'
print('Hello, %s. Will you go to the %s at %s this
%s at %s?' % (name, event, where, when, time))
Hello, Alice. Will you go to the party at the pool
this Saturday at 6:00pm?
>>>
String interpolation can make your code much easier to type and read, rather than using
several + concatenation operators.
The final line has the print() call with a string with conversion specifiers, followed
by the % sign, followed by a set of parentheses with the variables in them. The first
variable name will be used for the first %s , the second variable with the second %s and so
on. The Python interpreter will give you an error if you do not have the same number of %s
conversion specifiers as you have variables.
Another benefit of using string interpolation instead of string concatenation is that
interpolation works with any data type, not just strings. All values are automatically
converted to the string data type. (This is what the s in %s stands for.) If you typed this
code into the shell, you'd get an error:
Search WWH ::




Custom Search