Today we’ll be talking about string concatenation and repetition. Concatenation and repetition work with all sequences, not only strings.
String Concatenation
![string concatenation](https://i0.wp.com/prosperocoder.com/wp-content/uploads/2020/07/chain-722283_1920-1.jpg?resize=581%2C215&ssl=1)
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
![string repetition](https://i0.wp.com/prosperocoder.com/wp-content/uploads/2020/07/penalty-2290628_1920.jpg?resize=435%2C325&ssl=1)
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: