繁体   English   中英

如何使函数在同一行上多次打印,例如print('test')* 3

[英]How to make a function print many times on the same line, e.g. print('test')*3

假设我有代码(尽管它什么也没做,只是一个例子)

def myprint():
    print("foobar")
foo = random.randint(1, 6)
myprint() * foo    #Obviously doesn't work

我要执行的操作是执行print() 'foo'次。 我该怎么做呢?

您可以将代码更改为此:

def myprint(times):
    print(times*"foobar")
foo = random.randint(1, 6)
myprint(foo)

“ pythonic”方式是使用for循环的:

for n in range(foo):
    printfunc()

(请注意,如果您像在python 3中一样定义打印,则将用自己的遮罩原始print )。

for i in range(foo):
    print('test')

如果您真的想将其用作返回任意内容(通常非常糟糕,或者至少极其骇人听闻的形式)的表达式...

[print('test') for _ in range(foo)]

或者,如果您想对此一目了然,并且使阅读代码的人烦恼:

import random
print('\n'.join(["foo" for _ in range(random.randint(1,6))]))

这就是为什么您不应该调用自己的函数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()


>>>

哎呀,现在您已经覆盖了内置print因此您无法再使用它来实际打印内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM