Today we’ll be talking about string concatenation and repetition. Concatenation and repetition work with all sequences, not only strings.
String Concatenation
If we put string literals next to each other (with or without spaces), they will be joined into one string. This is called concatenation:
>>> "Hello " "kids."
'Hello kids.'
>>> "Hello ""kids."
'Hello kids.'
This only works with string literals. If we try to concatenate string variables this way, we’ll get an error:
>>> greeting = "Hello "
>>> greeting "kids."
File "<stdin>", line 1
greeting "kids."
^
SyntaxError: invalid syntax
We usually concatenate strings using the + sign. This is definitely necessary if we have string variables, but we usually also use the + sign for literals:
>>> "Hello" + " " + "kids!" # literals
'Hello kids!'
>>> daughter = "Alice" # variables
>>> son = "Josh"
>>> "I have a present for " + daughter + " and " + son + "."
'I have a present for Alice and Josh.'
String Repetition
We use the multiplication operator * with strings to repeat them:
>>> "It's s" + "o" * 10 + " good!"
"It's soooooooooo good!"
>>> 'ha ' * 20
'ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha '
>>> question = "Were you shocked?"
>>> answer = question[10:12] + " "
>>> answer * 5
'ho ho ho ho ho '
We can also use the augmented assignment operator *=
So, a *= b is the same as a = a * b
>>> pattern1 = "-oo-"
>>> pattern1 = pattern1 * 3
>>> pattern1
'-oo--oo--oo-'
>>> pattern2 = "=XX="
>>> pattern2 *= 3
>>> pattern2
'=XX==XX==XX='
Here’s the video version of this article: