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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.