简单的问题,我想在我调用的每个print
的前面附加文字,例如,如果我将文字设置为hello
并运行它:
print 'hello there'
print ' hi again'
它会打印出来:
hellohello there
hello hi again
有没有办法这样做,而不使用函数来代替print
?
答案 0 :(得分:3)
您可以按照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建议的那样,你可以避免使用sys调用:
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")
答案 1 :(得分:1)
您无法更改Python 2的print语句,但您可以编写自己的类文件对象并使用它:
class PrefixedFile(object):
def __init__(self, f, prefix):
self.f = f
self.prefix = prefix
def write(self, s):
s = s.replace("\n", "\n"+self.prefix)
self.f.write(s)
sys.stdout = PrefixedFile(sys.stdout, "hello: ")
print "One"
print "Two"
请注意,此代码不能正常工作,因为它在第一行缺少前缀,并在最后添加一个前缀,但您明白了! :)
答案 2 :(得分:0)
尽管Jon Cage的回答是替换print()
函数的好方法,但我建议使用自己的打印函数(使用Jon的代码):
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 my_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
print('hello', end='')
print(*args, **kwargs)
与Jon的答案唯一的区别是你不会覆盖内置的 print()
(“猴子修补”)。我提倡这样做而不是修改print()
,因为这会使您的代码更易于维护,因为每个人都希望print()
成为内置代码。
在print()
中使用print
功能代替my_print()
语句,提供greater flexibility。