简单的问题,我想将文本附加到我调用的每个 print
的前面,例如,如果我将文本设置为 hello
并运行以下命令:
print 'hello there'
print ' hi again'
它会打印这个:
hellohello there
hello hi again
有什么方法可以做到这一点,而不使用函数来代替 print
吗?
最佳答案
您可以按照DevPlayer's post here on StackOverflow覆盖打印,此处稍作修改:
from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string,
# Python comments or blank lines before the __future__ line.
import sys
def print(*args, **kwargs):
"""My custom print() function."""
# Adding new arguments to the print function signature
# is probably a bad idea.
# Instead consider testing if custom argument keywords
# are present in kwargs
sys.stdout.write('hello')
return __builtins__.print(*args, **kwargs)
print ("hello there")
print (" hi again")
[编辑] ...或者按照 DSM 的建议,您可以通过以下方式避免系统调用:
from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string,
# Python comments or blank lines before the __future__ line.
def print(*args, **kwargs):
"""My custom print() function."""
# Adding new arguments to the print function signature
# is probably a bad idea.
# Instead consider testing if custom argument keywords
# are present in kwargs
__builtins__.print('hello',end='')
return __builtins__.print(*args, **kwargs)
print ("hello there")
print (" hi again")
关于python - 附加到每条打印的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11006199/