How do I print a number n times in python? [duplicate]

大兔子大兔子 提交于 2021-02-05 12:29:20

问题


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.


回答1:


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)



回答2:


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)



回答3:


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.



来源:https://stackoverflow.com/questions/56091904/how-do-i-print-a-number-n-times-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!