Problem Formulation and Solution Overview
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.
Method 1: Use print() and multiplication operator
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
Method 2: Use a For Loop and range()
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.
print() statement outputs a line to the terminal, with each iteration as shown below.
Method 3: Use the
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
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.
💡Note: The newline character (
\n) caused the last line (line 3) to have an additional blank line.
Method 4: Use itertools.repeat()
import itertools print(list(itertools.repeat('HELP ME', 3)))
Above, imports the
Method 5: Use a DataFrame
This method uses a DataFrame and an empty column to assign a default value.
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))
Then, only a few columns of
finters.csv are read into the DataFrame
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.
At university, I found my love of writing and coding. Both of which I was able to use in my career.
During the past 15 years, I have held a number of positions such as:
In-house Corporate Technical Writer for various software programs such as Navision and Microsoft CRM
Corporate Trainer (staff of 30+)
Implementation Specialist for Navision and Microsoft CRM
Senior PHP Coder