2

print簡単な質問です。たとえば、テキストをに設定してhelloこれを実行した場合、呼び出すすべてのテキストの前にテキストを追加したいと思います。

print 'hello there'
print ' hi again'

これを印刷します:

hellohello there
hello hi again

代わりにそれを使用する関数を使用せずに、これを行う方法はありprintますか?

4

3 に答える 3

3

StackOverflowでのDevPlayerの投稿に従って、印刷をオーバーライドできますが、ここで少し変更されています。

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()代わりに独自の印刷関数を使用することをお勧めします(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() 関数を使用すると、柔軟性が向上します。printmy_print()

于 2012-06-12T23:33:38.887 に答える