Skip to content

Computer Science · Ch 8 — Strings

Repetition

8.3.2

Repetition

Python can produce a string made of several copies of a given string using the repetition operator, written as the asterisk symbol *. One operand is the string and the other is an integer saying how many times to repeat it; the result is the string written out that many times, back to back.

>>> s = 'Echo'      # assign the string 'Echo' to s
>>> s * 2           # repeat the value of s two times
'EchoEcho'
>>> s * 5           # repeat the value of s five times
'EchoEchoEchoEchoEcho'

As with concatenation, no separator is inserted between the copies — the repetitions run together as one continuous string.

Note: the original string is untouched by the operation. s still holds 'Echo' after s * 5; the repetition operator, like every string operation, returns a new string rather than modifying the old one:

>>> s               # unchanged after the repetitions …