How to Repeat a String in Python Without Using a Loop?

In Python, you can repeat a string "n" number of times without using a loop, in the following ways:

Using Repetition Operator

Perhaps the simplest way to repeat a string "n" number of times in Python is to use the repetition operator (*), for example, like so:

foo = 'quack!' * 3

print(foo) # "quack!quack!quack!"

You can also use *= to achieve the same:

foo = 'quack!'
foo *= 3

print(foo) # "quack!quack!quack!"

Using itertools.repeat() With str.join()

The str.join() method takes an iterable as an argument:

str.join(iterable)

Therefore, to repeat a string "n" number of times, you can simply pass itertools.repeat() as an argument to it, for example, like so:

import itertools as it

foo = ''.join(it.repeat('quack!', 3))

print(foo) # "quack!quack!quack!"

This works because the itertools.repeat() method creates an iterator that returns the same string repeated a specified number of times, which the str.join() method joins together using the empty string as a separator.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.