-2

How do I print a number n times in Python?

I can print 'A' 5 times like this:

print('A' * 5) AAAAA

but not 10, like this:

print(10 * 5) 50

I want the answer to be 10 10 10 10 10

How do I escape the mathematical operation in print()?

I am not asking how to print the string '10' n times, I am asking how to print the number 10 n times.

Luther_Blissett
  • 327
  • 1
  • 6
  • 16
  • Figured it out: `print([10] * 5)` – Luther_Blissett May 11 '19 at 16:00
  • 2
    This is producing a list, whereas your expected output is a string. The correct answer is the one you can see in all the answers to your question.. – yatu May 11 '19 at 16:03
  • R and Python are different @GaryNapier, you would need to ensure whatever you want to repeatedly print via * operator is a string :) – Devesh Kumar Singh May 11 '19 at 16:39
  • I don't recommend using the * operand. It saves you a few lines, but is less clear than a basic loop. Shortcuts often increase the chance for hidden bugs and code that is harder for others to read. For example, if you skip through your code in the future, you might just as easily see that * and assume the output is 50, instead of 10 10 10 10 10 – pinkwaffles Sep 05 '19 at 22:18

3 Answers3

4

10*5 actually does multiplication and ends up giving you 50, but when you do '10 '*5, the * operator performs the repetition operator, as you see in 'A' * 5 for example

print('10 ' * 5)

Output will be 10 10 10 10 10

Or you can explicitly convert the int to a string via str(num) and perform the print operation

print((str(10)+' ') * 5)
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1

If you have the number as a variable:

number = 10
print("f{number} " * 5)

Or without f-strings:

number = 10
print((str(number)) + ' ') * 5)

 

If you just want to print a number many times, just handle it as as string:

print("10 " * 5)
ruohola
  • 21,987
  • 6
  • 62
  • 97
0

This trick only works for strings.

print('10' * 5)

Will print:

1010101010

That's because the * operator is overloaded for the str class to perform string repetition.

rdas
  • 20,604
  • 6
  • 33
  • 46