2

简单的问题,我想将文本附加到每个print调用的前面,例如,如果我将文本设置为hello并运行:

print 'hello there'
print ' hi again'

它会打印这个:

hellohello there
hello hi again

有没有办法做到这一点,而不使用函数来使用它而不是print

4

3 回答 3

3

您可以根据DevPlayer 在 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")
于 2012-06-12T23:27:27.283 回答
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"

请注意,此代码不太有效,因为它在第一行缺少前缀,并在最后添加了一个前缀,但您明白了!:)

于 2012-06-12T23:33:07.043 回答
0

尽管 Jon Cage 的回答是替换print()函数的好方法,我还是建议改用你自己的 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)

与乔恩答案的唯一区别是您不会覆盖内置 print()(“猴子补丁”)。我提倡这样做而不是修改print(),因为这使您的代码更易于维护,因为每个人都希望print()成为内置代码。

使用print() 函数而不是print语句 inmy_print()提供了更大的灵活性

于 2012-06-12T23:33:38.887 回答