Python provides a wide variety of features to work with strings. In this tip, you'll learn about string concatenation and repetition.

The + operator is one of the ways to concatenate two strings. The operands can be any expression that results in a string value and you can use any of the different ways to specify a string literal. Another option is to use f-strings. Here are some examples:

>>> s1 = 'hello'
>>> s2 = 'world'
>>> print(s1 + ' ' + s2)
hello world

>>> f'{s1} {s2}'
'hello world'

>>> s1 + r'. 1\n2'
'hello. 1\\n2'

Another way to concatenate is to simply place any kind of string literal next to each other. You can use zero or more whitespaces between the two literals. But you cannot mix an expression and a string literal. If the strings are inside parentheses, you can also use newline characters to separate the literals and optionally use comments.

>>> 'hello' r'. 1\n2'
'hello. 1\\n2'

>>> print('apple'
...       '-banana'
...       '-cherry')
apple-banana-cherry

You can repeat a string by using the * operator between a string and an integer. You'll get an empty string if the integer value is less than 1.

>>> style_char = '-'
>>> print(style_char * 50)
--------------------------------------------------

>>> word = 'buffalo '
>>> print(8 * word)
buffalo buffalo buffalo buffalo buffalo buffalo buffalo buffalo 

Video demo:


info See also my 100 Page Python Intro ebook.