How to Repeat a String Multiple Times in Python

Problem Formulation and Solution Overview

In this article, you’ll learn how to repeat a string multiple times in Python.

Over your career as a Python coder, you will encounter situations when a string needs to be output/displayed a specified number of times. The examples below offer you various ways to accomplish this task.


πŸ’¬ Question: How would we write Python code that repeats a string multiple times?

We can accomplish this task by one of the following options:


Method 1: Use print() and multiplication operator

This method uses Python’s built-in print() statement combined with a multiplication operator to output a string multiple times.

saying = 'Wash. Rinse. Repeat!\t'
print(saying * 3)

Above declares the string ‘Wash. Rinse. Repeat!‘ followed by a tab character, also known as an escape character (\t). The results save to saying.

Next, the print() statement outputs the saying three (3) times, with the escape character (\t) between each saying on the same line.

Wash. Rinse. Repeat! Wash. Rinse. Repeat! Wash. Rinse. Repeat!

Method 2: Use a For Loop and range()

This method uses a for loop with the range() function to iterate and output a string a set number of times.

for i in range(3):
    print('I never want to grow up!')

Above instantiates a For loop with the range() function. This function accepts a start position (not required), a stop position (required) and a step (not required). The start position is always zero (0) unless otherwise stated. The stop position is always stop-1.

The print() statement outputs a line to the terminal, with each iteration as shown below.

I never want to grow up!
I never want to grow up!
I never want to grow up!

Method 3: Use the input() function

This method prompts the user to enter a specified number of times to repeat a string using the int() and input() functions.

num = int(input('Number of times to repeat a string? '))
print('Hello World!\n' * num)

Above, prompts the user to enter how many times a string will display. Their answer is converted to an integer (int()) and saved to num.

Next, the string ‘Hello World‘ is output to the terminal. The newline character is appended (\n) so the output displays on a new line each time.

For this example, the number three (3) was entered.

Hello World!
Hello World!
Hello World!

πŸ’‘Note: The newline character (\n) caused the last line (line 3) to have an additional blank line.


Method 4: Use itertools.repeat()

This method uses Python’s built-in library itertools to call the repeat() function, which repeats a number or a string a stated number of times.

import itertools   
print(list(itertools.repeat('HELP ME', 3)))

Above, imports the itertools library.

Then, the repeat() function is called and passed two (2) arguments: the string to repeat and the number of times to repeat. This is then converted to a list and output to the terminal.

['HELP ME', 'HELP ME', 'HELP ME']

Method 5: Use a DataFrame

This method uses a DataFrame and an empty column to assign a default value.

The Pandas library must be installed and imported to run this code error-free. Click here for installation instructions.

To follow along, click here to download the finxters.csv file and move this file to the current working directory.

import pandas as pd 
df = pd.read_csv('finxters.csv', usecols=['FID', 'First_Name', 'Last_Name'])
df['Award'] = 'TBD'
df.to_csv('finxter1.csv')
print(df.head(3))

Above, imports the Pandas library to read in the CSV file and work with a DataFrame.

Then, only a few columns of finters.csv are read into the DataFrame df.

Next, the DataFrame df is saved to a new CSV file, finxters1.csv and placed in the current working directory.

Finally, the output is sent to the terminal. For this example, only three (3) rows are displayed.

FIDFirst_NameLast_NameAward
030022145SteveHamiltonTBD
130022192AmyPullisterTBD
230022331PeterDunnTBD

Summary

These five (5) methods of printing a string multiple times should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Regex Humor

Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee. (source)