next up previous contents
Next: Repetition Up: String Operations Previous: String Operations   Contents


Concatenation

The addition operator (+) takes on the role of concatenation when used with strings, that is, the result of ``adding'' two strings together is a new string which consists of the original strings put together:

>>> first = 'black'
>>> second = 'jack'
>>> first + second
'blackjack'
No space or other character is inserted between concatenated strings. If you do want a space, you can simply add it:
>>> first + " " + second
'black jack'
When the strings you want to concatenate are literal string constants, that is, pieces of text surrounded by any of the quotes that python accepts, you don't even need the plus sign; python will automatically concatenate string constants that are separated by whitespace:
>>> nums = "one "  "two "  "three "
>>> nums
'one two three '

You can freely mix variables and string constants together -- anywhere that python expects a string, it can be either a variable or a constant:

>>> msg = """Send me email
... My address is """
>>> msg + "me@myplace.com"
'Send me email\012My address is me@myplace.com'
Notice that the newline which was entered in the triple quoted string appears as \012, the octal representation of the (non-printable) newline character. When you use the print command, the newline is displayed as you would expect:
>>> print msg + 'me@myplace.com'
Send me email
My address is me@myplace.com

Remember that python considers the type of an object when it tries to apply an operator, so that if you try to concatenate a string and a number, you'll have problems:

>>> x = 12./7.
>>> print 'The answer is ' + x
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: illegal argument type for built-in operation
The number (x) must first be converted to a string before it can be concatentated. Python provides two ways to do this: the core function repr, or the backquote operator (``). The following example shows both of these techniques used to solve the problem of concatenating strings and numbers:
>>> print 'The answer is ' + repr(x)
The answer is 1.71428571429
>>> print 'The answer is ' + `x`
The answer is 1.71428571429
Notice that python uses its default of 12 significant figures; if you want more control over the way numbers are converted to strings, see Section 5.2, where the percent operator (%) for string formatting is introduced.

When you want to concatenate lots of strings together, the join method for strings (Section 2.4.4), or the join function in the string module (Section 8.4.2) are more convenient.


next up previous contents
Next: Repetition Up: String Operations Previous: String Operations   Contents
Phil Spector 2003-11-12