在python中有一种简单的方法可以为多个打印添加一个永久字符(或字符串)吗?
示例:
add_string('Hello ')
print('World')
print('You')
会输出
Hello World
Hello You
有没有办法在不更改代码的以下部分的情况下执行此操作:
print('World')
print('You')
答案 0 :(得分:1)
您可以让add_string
函数覆盖内置print
函数:
from __future__ import print_function # for python 2.x
def add_string(prefix):
def print_with_prefix(*args, **kwargs):
if prefix:
args = (prefix,) + args
__builtins__.print(*args, **kwargs)
global print
print = print_with_prefix
您可以设置或取消设置前缀,同时保留传递给print
的任何其他参数。
print("foo") # prints 'foo'
add_string(">>>")
print("bar") # prints '>>> bar'
print("bar", "42", sep=' + ', end="###\n") # prints '>>> + bar + 42###'
add_string(None)
print("blub") # prints 'blub'
如果您使用的是print
语句(即print "foo"
而不是print("foo")
),那么您必须使用自定义编写者重新定义sys.stdout
:
import sys
stdout = sys.stdout
def add_string(prefix):
class MyPrint:
def write(self, text):
stdout.write((prefix + text) if text.strip() else text)
sys.stdout = MyPrint() if prefix else stdout
答案 1 :(得分:0)
因为你想把它添加到几个,但不是全部,最好使用一个自制函数添加一些东西,所以你只需要为你想要添加它的情况调用该函数,并且不要在你不想添加它的情况下
def custom_print(text):
print('Hello ' + text)
custom_print('World') # output: Hello World
答案 2 :(得分:0)
尝试这样:
def my_print(custom="Hello",my):
print(custom + ' ' + my)
my_print(my='world')
my_print(my="you")
my_print(custom="Hey",'you')
输出:
Hello world
Hello you
Hey you
您可以使用kwarg = Value
形式的自定义键参数
有关详情,请点击https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments
答案 3 :(得分:0)
from __future__ import print_function # needed for python 2.7
def print(*args, **kwargs):
return __builtins__.print("Hello",*args, **kwargs)
print('World')
Hello World