Python Practice › Basic Programs › Program 4
Repeat a string 5 times
Write a Python program to repeat a given string 5 times.
Input
str1 = "SQATools"
Output
SQAToolsSQAToolsSQAToolsSQAToolsSQATools
Approach
- Multiply the string by 5. In Python,
string * nrepeats the string n times.
Solution 1: the * operator
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
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.
Learn the concept
New to this topic? Read the lesson, then come back.