Efficiently Repeat a String to a Certain Length in Python



In Programming, it is useful to repeat or pad a string up to a certain length. Whether generating the formatted output, filling templates, or being able to repeat the string to a specific length can save time.

In this article, we are exploring an efficient way to repeat a string to a certain length. Python provides various ways, such as using multiplication, string slicing, and built-in methods like ljust(), rjust(), and zfill().

Using String Multiplication

The first approach is by using the * operator. Here, we are going to repeat the string to a specific length using the '* operator' and slice it to fit the required size.

Example

Let's look at the following example, where we are going to perform the string multiplication along with slicing.

str1 = "TP"
x = 11
result = (str1 * ((x // len(str1)) + 1))[:x]
print(result)

The output of the above program is as follows -

TPTPTPTPTPT

Using Python str.ljust() Method

In this approach, we are going to use the Python .ljust() method. It is used to left-align the string with the width specified. Here, we are repeating the string enough times and padding with spaces if shorter, and the ljust() method ensures the final result has a length of characters by adding the spaces to the right.

Syntax

Following is the syntax of Python str.ljust() method -

string.ljust(length, character)

Example

Consider the following example, where we are going to use the str.ljust() method for left-justified padding.

str1 = "Hello"
x = 5
result = (str1 * x).ljust(x)
print(result)

The output of the above program is as follows -

HelloHelloHelloHelloHello

Using Python itertools.cycle() Function

The Python itertools.cycle() function is used to create an iterator that repeats the elements of an iterable indefinitely in the same order. It is commonly used for cycling through elements in a sequence repeatedly.

Syntax

Following is the syntax of the Python itertools.cycle() function -

itertools.cycle(iterable)

Example

In the following example, we are going to use the itertools.cycle() for repeating the string along with the islice() to slice the required number of characters.

from itertools import cycle, islice
str1 = "ABBA"
x = 12
result = ''.join(islice(cycle(str1), x))
print(result)

The output of the above program is as follows -

ABBAABBAABBA
Updated on: 2025-06-10T19:19:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started