Python – Repeat a String N Times

Python – Repeat a String N Times

Given a string myStr and a count n, we have to concatenate the string myStr to itself such that the given string appears in the resulting string for n times.

To repeat given string N times in Python, you can use Multiple Concatenation operator *. The operator takes the string and the number as operands, and returns a string self-concatenated by given number of times. Or you can also use a For loop to iterate for n number of times and concatenate the given string to a resulting string in the loop.

1. Repeat string for n times using Multiple Concatenation operator in Python

In this example, we are given a string in x and we are given a count value in n. We have to repeat the string in x for n number of times.

Steps

  1. Given a string in x, and count in n.
  2. Use Multiple Concatenation operator * and pass x and n as operands.
  3. The operator returns a new string where the string value in x is repeated for n times. You may store it in a variable, and print it to output.

Program

The complete program to repeat a given string for n number of times using Multiple Concatenation operator.

Python Program

# Given string
x = 'Apple'

# Given count (n)
n = 4

# Repeat string for n times
x_repeated = x * 4

print(f"Original String : {x}")
print(f"Repeated String : {x_repeated}")
Run Code

Output

Original String : Apple
Repeated String : AppleAppleAppleApple

2. Repeat string for n times using For loop in Python

In this example, we are given a string in x and we are given a count value in n. We have to repeat the string in x for n number of times.

Steps

  1. Given a string in x, and count in n.
  2. Take a variable, say x_repeated, to store the repeated string.
  3. Write a For loop that iterate over range(n), and inside the For loop, concatenate string in x to x_repeated.
  4. After the completion of For loop, x_repeated contains the repeated string value.

Program

The complete program to repeat a given string for n number of times using For loop.

Python Program

# Given string
x = 'Apple'

# Given count (n)
n = 4

# Repeat string for n times
x_repeated = ''
for i in range(4):
    x_repeated += x

print(f"Original String : {x}")
print(f"Repeated String : {x_repeated}")
Run Code

Output

Original String : Apple
Repeated String : AppleAppleAppleApple

Summary

In this tutorial of Python Examples, we learned how to repeat a given string for specific number of times, using Multiple Concatenation operator or For loop, with the help of well detailed examples.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us