Print a number N times in Python

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

Print a number N times in Python #

To print a number N times:

  1. Use the str() class to convert the number to a string.
  2. Use the multiplication operator to repeat the number N times.
  3. Use the print() function to print the result.
main.py
my_num = 100 # ✅ print a number N times using multiplication print(str(my_num) * 2) # 👉️ 100100 # ✅ print a number N times using formatted string literal print(f'{my_num}' * 2) # 👉️ 100100 # ✅ print a number N times with space print((str(my_num) + ' ') * 2) # 👉️ 100 100 print(f'{my_num} ' * 2) # 👉️ 100 100

We first used the str() class to convert the number to a string.

You can use the multiplication operator to repeat a string N times.

main.py
my_num = 100 print(str(my_num) * 2) # 👉️ 100100 print((str(my_num) + ' ') * 2) # 👉️ 100 100
If you need to print spaces between the numbers, use the addition (+) operator to add a space before using the multiplication operator.

If you use this approach, there will be a trailing space after the end of the string.

main.py
my_num = 100 result = (str(my_num) + ' ') * 2 print(result) print(repr(result)) # 👉️ '100 100 '

You can use the str.strip() method to remove the leading and trailing whitespace characters from the string.

main.py
my_num = 100 result = ((str(my_num) + ' ') * 2).strip() print(result) print(repr(result)) # 👉️ '100 100'

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

Print a number N times using a formatted string literal #

Use a formatted string literal to print a number N times, e.g. print(f'{my_num}' * 2). Formatted string literals (f-strings) let us include expressions and variables inside of a string by prefixing the string with f.

main.py
my_num = 100 print(f'{my_num}' * 2) # 👉️ 100100 print(f'{my_num} ' * 2) # 👉️ 100 100

The example uses a formatted string literal to repeat a number N times.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
my_str = 'The number is:' my_int = 5000 result = f'{my_str} {my_int}' print(result) # 👉️ The number is: 5000

Make sure to wrap expressions in curly braces - {expression}.

If you need to separate the numbers with a space, add a space after the expression.

main.py
my_num = 100 print(f'{my_num} ' * 2) # 👉️ 100 100 print(repr(f'{my_num} ' * 2)) # 👉️ '100 100 '

When using this approach there is a trailing space added at the end of the string.

You can use the str.strip() method if you need to remove it.

main.py
my_num = 100 result = (f'{my_num} ' * 2).strip() print(result) # 👉️ 100 100 print(repr(result)) # 👉️ '100 100'
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.