PythonPython StringsPython string repetition

What is string repetition?

Question 65 of 88 · Updated

On this page

String repetition creates a string containing a specified number of consecutive copies of another string. Use the multiplication operator * with a string and an integer count: "ab" * 3 evaluates to "ababab".

Unlike numerical multiplication, repetition copies a sequence of text rather than calculating a numeric product. It is useful for separators, padding, repeating patterns and small deterministic text fixtures.

1. Syntax and boundary cases#

PYTHON
print('ab' * 3, 3 * 'ab') print(repr('ab' * 0), repr('ab' * -2), repr('' * 5))

Output:

ababab ababab
'' '' ''

For ordinary str and int operands, either operand order works.

ExpressionResult
'ab' * 3'ababab'
'ab' * 1'ab'
'ab' * 0Empty string
'ab' * -2Empty string
'' * 5Empty string

A nonpositive repetition count yields an empty string; it does not reverse the input or raise an error merely because it is negative. An empty pattern remains empty for ordinary valid repetition counts. Python does not insert spaces or other separators between copies.

For a string of length m and integer count n, the resulting length is m times max(0, n), provided the operation succeeds.

Loading diagram…

The diagram represents the resulting sequence, not three separately allocated intermediate strings. An interpreter can construct the final result directly.

2. The repetition count must support integer indexing#

PYTHON
class Copies: def __index__(self): return 3 print('x' * Copies()) print(repr('x' * False), 'x' * True)

Output:

xxx
'' x

The integer-index protocol allows a suitable object implementing __index__ to specify an exact integer count. Boolean values also work because bool is a subclass of int, although explicit integer counts are generally clearer.

An object that provides only __int__ is not necessarily accepted by repetition. A float such as 2.0, a string such as '2', or None cannot be used as a repetition count for ordinary strings; all three raise TypeError.

When the count comes from an external text field, parse it according to the application's integer grammar and validate its permitted range. Do not silently truncate a fractional value with int merely to make an operation succeed.

3. Repetition, augmented assignment and precedence#

PYTHON
text = 'go' original = text text *= 2 print(text, original) print('ha' * 2 + '!', ('ha' + '!') * 2)

Output:

gogo go
haha! ha!ha!

The augmented assignment rebinds text to the repeated value. The original string remains unchanged. This follows the immutability rules covered earlier in the curriculum.

Multiplication has higher precedence than addition, so 'ha' * 2 + '!' repeats only 'ha' and then appends the exclamation mark. Parentheses in the second expression make the complete 'ha!' pattern the repeated unit.

Distinguish repetition from concatenation: concatenation combines potentially different strings, whereas repetition uses the same string value for every copy.

4. Practical example: fill an exact number of code points#

Suppose a plain-text test fixture needs a repeating pattern with an exact length, even if the requested width is not a multiple of the pattern length.

PYTHON
def fill_pattern(pattern, width): if not pattern or width < 0: raise ValueError('invalid pattern or width') copies, remainder = divmod(width, len(pattern)) return pattern * copies + pattern[:remainder] print(fill_pattern('abc', 8)) print(repr(fill_pattern('abc', 0)))

Output:

abcabcab
''

The quotient determines the number of complete pattern copies; the remainder determines the extra prefix needed. For width 8 and pattern 'abc', divmod(8, 3) returns (2, 2), so the result contains two copies followed by 'ab'.

The function assumes a str pattern and an integer width. It rejects an empty pattern because there is no nonempty unit to fill the requested length. The width measures Unicode code points, not encoded bytes or terminal display columns. Add an explicit output-size limit if the width is supplied externally.

For simple one-character padding, multiplication is often sufficient. For padding an existing string to a minimum width, str.ljust, str.rjust and str.center may express the intention more clearly.

5. Bound the output before allocating memory#

Repetition materializes text rather than returning a lazy view. An externally supplied count can request an impractically large result. Validate both the count and the resulting size before attempting the multiplication.

PYTHON
def bounded_repeat(text, count, limit=1000): if not isinstance(text, str): raise TypeError('expected str') if type(count) is not int: raise TypeError('expected int') if count < 0 or count > limit: raise ValueError('count outside allowed range') if len(text) * count > limit: raise ValueError('output too long') return text * count print(bounded_repeat('é', 3)) try: bounded_repeat('abc', 400) except ValueError as exc: print(exc)

Output:

ééé
output too long

This application policy deliberately rejects negative counts and Boolean counts, even though ordinary Python repetition accepts them. It assumes limit is a trusted nonnegative integer configuration value.

The code-point limit prevents large ordinary text results, but is not an exact memory or encoded-byte budget. A UTF-8 output boundary must also account for encoded size. A streaming destination may allow repeated fragments to be written incrementally rather than assembled into one giant string, provided total work and output volume are still bounded.

Extremely large native repetition requests can raise OverflowError or MemoryError, depending on the size and implementation. Do not deliberately allocate enormous strings to demonstrate these errors.

6. Complexity and Unicode considerations#

For an ordinary string of length m and a positive count n, let L = m*n. When a nontrivial result must be materialized, typical CPython time and result storage are proportional to L. Trivial cases, including empty results or a single copy, may use existing immutable objects. There is no promise that every repetition allocates a distinct object.

Repetition preserves the code-point sequence of the pattern exactly. It does not automatically normalize Unicode, separate grapheme clusters or account for display width. Repeating a combining mark or a multi-code-point emoji is therefore not equivalent to filling a fixed number of display columns.

Do not confuse string repetition with repeating a list of mutable objects. List repetition can create multiple references to the same mutable element, as explained in the earlier mutability lesson. Ordinary string repetition instead produces an immutable text value.

7. Common mistakes#

MistakeCorrect approach
Expecting 'ab' * 3 to insert spacesInclude separators explicitly or use join
Using a float countRequire an exact integer count
Expecting a negative count to reverse textUse a reverse slice for code-point reversal
Expecting *= to mutate existing string valuesTreat it as rebinding
Repeating unbounded external inputValidate count and output length before allocation

If the desired output contains a separator only between repetitions, use a separator-based join over a suitable bounded collection or iterable. Simply repeating a pattern with a trailing separator also repeats that separator after the final copy.

Interview-ready answer#

String repetition in Python uses the * operator with a string and an integer count. For example, 'ab' * 3 produces 'ababab'. Zero or negative counts return an empty string, while unsupported count types raise TypeError. Strings remain immutable, including when using *=. Repetition preserves the original code-point sequence without inserting separators. For a nontrivial materialized result, the usual time and space cost is proportional to the output length, so validate externally supplied counts and output-size limits.

Official references#

Verification note: Five runnable example groups matched their expected output on CPython 3.13.5. Three unsupported-count TypeError tests and 500 seeded randomized comparisons against explicit joining passed. The fenced Mermaid diagram was manually reviewed; local Mermaid parser/CLI and public-site rendering were unavailable. Oversized allocations were deliberately not attempted. Official references are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design