Repeat a string 5 times
Write a Python program to repeat a given string 5 times.
str1 = "SQATools"
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)SQAToolsSQAToolsSQAToolsSQAToolsSQATools
Line by line
* 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)SQAToolsSQAToolsSQAToolsSQAToolsSQATools
Line by line
Start with an empty string.
The loop runs 5 times and appends the text each time. _ is used as the loop variable because its value is not needed.
Prints the same result as Solution 1.
Learn the concept
New to this topic? Read the lesson, then come back.