Open In App

How to Repeat a String in Python?

Last Updated : 12 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Repeating a string is a simple task in Python. We can create multiple copies of a string by using built-in features. This is useful when we need to repeat a word, phrase, or any other string a specific number of times.

Using Multiplication Operator (*):

Using Multiplication operator (*) is the simplest and most efficient way to repeat a string in Python. It directly repeats the string for a specified number of times.

Python
s = "Hello! "

# Repeat the string 3 times
r= s * 3  
print(r)

Output
Hello! Hello! Hello! 

Let's take a look on several ways to repeat string in python:

Using itertools.repeat()

This function in Python allows us to create an iterator that repeats a value multiple times. It's useful when we need a sequence of string for a specific number of iterations.

Python
import itertools

# Repeating a string using itertools.repeat
s = ''.join(itertools.repeat("Hello! ", 3))
print(s)

Output
Hello! Hello! Hello! 

Explanation:

  • itertools.repeat("Hello! ", 3): This generates an iterator that repeats the string "Hello! " exactly 3 times.
  • ''.join(...): This method merges the repeated strings into one continuous string, resulting in "Hello! Hello! Hello! ".

Using for Loop

Repeating a string using a for loop is a more flexible method. You iterate a specified number of times and append the string to a variable each time.

Python
s = ""

# for loop to repeat a string
for _ in range(4): 
    s += "Hello!" 
print(s)

Output
Hello!Hello!Hello!Hello!

Using numpy.repeat()

We can also repeat a string using numpy.repeat(). This method repeats the string a specified number of times and returns the result as a array, which can be easily converted into a single string.

Python
import numpy as np

# Repeating the string 
s = np.repeat("Hello! ", 3)

# Joining array into a single string
result = ''.join(s)
print(result)

Output
Hello! Hello! Hello! 

Expalnation:

  • np.repeat("Hello! ", 3): This repeats the string "Hello! " 3 times and stores it in a numpy array.
  • ''.join(s): This repeated elements in the array into one continuous string, resulting in "Hello! Hello! Hello! "

Next Article

Similar Reads