Combining and Concatenating Strings in Python

You can concatenate strings in Python easily using the ‘+’ operator and also repeat a string using the ‘*’ operator.

>>> 'Hello' + ' ' + 'World!'
'Hello World!'
>>> 'Yeah!' * 6
'Yeah!Yeah!Yeah!Yeah!Yeah!Yeah!'
>>> ('Yeah!' + ' ') * 6
'Yeah! Yeah! Yeah! Yeah! Yeah! Yeah! '

The repeat operator can also take a variable or expression.

>>> num_repeats = 6
>>> ('Yeah!' + ' ') * num_repeats
'Yeah! Yeah! Yeah! Yeah! Yeah! Yeah! '
>>> num_repeats = 3
>>> ('Yeah!' + ' ') * num_repeats
'Yeah! Yeah! Yeah! '
>>> ('Yeah!' + ' ') * (num_repeats + 2)
'Yeah! Yeah! Yeah! Yeah! Yeah! '

You can also combine strings from a Python List into a new string using the join() method.

>>> parts = ['Hello', 'World']
>>> ' '.join(parts)
'Hello World'

Surprisingly you can also do the following without the ‘+’ operator. Although I’ld not recommend it as it does not make string concatenation explicit.

>>> greetings = 'Hello' ' ' 'World'
>>> greetings
'Hello World'

Leave a Reply

Your email address will not be published. Required fields are marked *