HOWTO · Python

How to Repeat String N Times in Python

Learn how to repeat a string a fixed number of times in Python and how to build a string up to a specified character length.

On this page

In Python, multiply a string by an integer to repeat the whole string a fixed number of times. To produce a string up to a target character length, repeat it enough times and slice the result. These approaches answer different needs: the first keeps every copy intact, while the second may end partway through a copy.

Repeat a String N Times with the * Operator in Python

Use the * operator when you know how many complete copies you need. The result is a new string containing the original text in sequence. Here is a small example:

print("ha" * 3)
hahaha

The output is hahaha. Multiplication by 0 produces an empty string. A negative repetition count also produces an empty string; if your application should reject such input, validate the count before multiplying. The count should be an integer.

If copies need a separator, call join() on a repeated sequence. For example, ", ".join(["ha"] * 3) places a comma and space between the copies, producing ha, ha, ha. The separator belongs between items; the * operator alone simply places the copies next to each other. For the usual fixed-count task, string multiplication is the clearest choice.

Repeat a String to a Specified Length in Python

A target-length task can end with only part of the last copy. Repeat the source enough times, then slice the result to the requested number of characters. This helper rejects a negative target length and reports that a positive length cannot be formed from an empty source string:

def repeat_to_length(text, target_length):
    if target_length < 0:
        raise ValueError("target_length must be nonnegative")
    if not text and target_length > 0:
        raise ValueError("text must not be empty for a positive target length")
    if target_length == 0:
        return ""

    copies = (target_length + len(text) - 1) // len(text)
    return (text * copies)[:target_length]

result = repeat_to_length("abc", 8)
print(result)
abcabcab

For the inputs shown, the output is abcabcab: two complete copies plus the first two characters of the next copy. The ceiling-division expression computes how many copies are needed, and slicing enforces the exact requested length.

A target length of 0 returns an empty string. An empty source string can produce only a target length of 0; the helper raises ValueError for a positive target. It also raises ValueError for a negative target so callers cannot silently receive a misleading result. If your application prefers a different policy, adjust those checks before using the helper.