[英]How to make a function print many times on the same line, e.g. print('test')*3
Let's say I have the code (although it doesn't do anything, just an example) 假设我有代码(尽管它什么也没做,只是一个例子)
def myprint():
print("foobar")
foo = random.randint(1, 6)
myprint() * foo #Obviously doesn't work
What I want it to do is carry out print()
'foo' times. 我要执行的操作是执行
print()
'foo'次。 How do I do this? 我该怎么做呢?
You can change your code to this one: 您可以将代码更改为此:
def myprint(times):
print(times*"foobar")
foo = random.randint(1, 6)
myprint(foo)
The "pythonic" way is with a for-loop: “ pythonic”方式是使用for循环的:
for n in range(foo):
printfunc()
(Note that if you define print like you did in python 3, you're masking the original print
with your own). (请注意,如果您像在python 3中一样定义打印,则将用自己的遮罩原始
print
)。
for i in range(foo):
print('test')
If you really want to do it as an expression that returns something arbitrary (typically very bad, or at least extremely hackish, form)... 如果您真的想将其用作返回任意内容(通常非常糟糕,或者至少极其骇人听闻的形式)的表达式...
[print('test') for _ in range(foo)]
Or if you want to be obscure about it and annoy people reading your code: 或者,如果您想对此一目了然,并且使阅读代码的人烦恼:
import random
print('\n'.join(["foo" for _ in range(random.randint(1,6))]))
This is why you shouldn't call your own function print
这就是为什么您不应该调用自己的函数
print
Python 3.2 (r32:88445, Dec 8 2011, 15:26:51)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
>>> def print():
... print("foobar")
...
>>> help(print)
Help on function print in module __main__:
print()
>>>
oops now you have overwritten the builtin print
so you can't use it to actually print stuff anymore 哎呀,现在您已经覆盖了内置
print
因此您无法再使用它来实际打印内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.