Repeat a string 5 times

EasyBasic Programs · 4 of 40

Write a Python program to repeat a given string 5 times.

Advertisement
Input
str1 = "SQATools"
Output
SQAToolsSQAToolsSQAToolsSQAToolsSQATools

Approach

  1. Multiply the string by 5. In Python, string * n repeats the string n times.

Solution 1: the * operator

Python
str1 = "SQATools"result = str1 * 5print(result)
Output
SQAToolsSQAToolsSQAToolsSQAToolsSQATools

Line by line

Line 2

* between a string and an integer repeats the string; no loop is needed.

Solution 2: a loop

Python
str1 = "SQATools"result = ""for _ in range(5):    result += str1print(result)
Output
SQAToolsSQAToolsSQAToolsSQAToolsSQATools

Line by line

Line 2

Start with an empty string.

Lines 3-4

The loop runs 5 times and appends the text each time. _ is used as the loop variable because its value is not needed.

Line 5

Prints the same result as Solution 1.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs