我正在修改打印功能,例如:
cg = "\u001b[32;1m"
stop = "\u001b[0m"
_print = print
def print(*args, **kw):
#color the word "CommandGeek" green
args = (arg.replace('CommandGeek', f'{cg}CommandGeek{stop}') if isinstance(arg, str) else arg for arg in args)
_print(*args, **kw)我想要做的是添加如下代码:
cg = "\u001b[32;1m"
stop = "\u001b[0m"
_print = print
def print(*args, **kw):
#color the word "CommandGeek" green
args = (arg.replace('CommandGeek', f'{cg}CommandGeek{stop}') if isinstance(arg, str) else arg for arg in args)
#Color entire the message green if "CommandGeek:" is in it.
if "CommandGeek:" in args:
args = cg + args + stop
_print(*args, **kw)但这不管用,只是什么都没印出来。我还试图在不修改args的情况下输入if语句,但它仍然什么也没做。这里发生了什么,如果消息中有"CommandGeek:“,我如何更改打印出来的值?
发布于 2022-02-01 17:32:12
没有高级结构,如生成器,列表理解或类似的。
理解星号(解包)和元组
首先,我们需要理解*args是一个名为args的参数,定义为varargs (多个参数作为元组)。请参阅(星号/星号)参数做什么?
请参见这个答案,它很好地解释了这一点:
在函数签名中使用
*args将所有位置参数打包到单个元组args中。如果您然后在函数体内的另一个函数调用中说*args,它会将它扩展回多个参数,
为什么要在这里使用?
这在函数定义def print(*args, **kw):中使用,以模仿与内置print函数相同的签名(参数),最初使用的是Python。在重新定义_print = print之前,可以将其视为拦截器。
其效果将是一个print函数,当某个关键字(此处"CommandGeek“找到)时,它会使用ANSI-colors (ANSI-转义码)自动高亮显示单词或输出。
你的任务
在功能体内实现注释(任务):
#color the word "CommandGeek" green
# locate the word
# surround it with ANSI-color code
#Color entire the message green if "CommandGeek:" is in it.
# locate the word
# surround the entire message with ANSI-color code您的输入(包含单词或命令的消息)由参数*args提供,我们知道该参数是将所有位置参数打包到一个元组(varargs)中。元组名为args。
GREEN = "\u001b[32;1m"
RESET = "\u001b[0m"
WORD = "CommandGeek"
# a testable function with debug-prints
def color(*args):
print(len(args))
colored = []
for a in args:
s = str(a)
if s.__contains__(WORD):
print("Found it in: " + s)
colored.append(s.replace(WORD, f"{GREEN}{WORD}{RESET}"))
else:
colored.append(a)
return colored
colored = color('Hello', 'World', 'CommandGeek')
print(colored) # prints the list or tuple (not colored)
print(*colored) # prints all with color if found (because unpacked)打印(在控制台中粗体原来是绿色的):
3. 在CommandGeek中找到的 Hello CommandGeek
现在我们只有一个词是有色的。接下来,如果至少有一个包含单词,那么让我们将整个消息(=所有args)涂上颜色。
GREEN = "\u001b[32;1m"
RESET = "\u001b[0m"
WORD = "CommandGeek"
def contains_word(*args):
for a in args:
s = str(a)
if s.__contains__(WORD):
return True
return False
tuple = ('Hello', 'World', 'CommandGeek') # define a tuple
should_color = contains_word(*tuple) # unpack a tuple as multiple args (varargs)
if should_color:
print(GREEN, *tuple, RESET) # prints all elements in color (unpacked)
else:
print(*tuple) # prints the tuple (unpacked, not colored)打印(在控制台中粗体原来是绿色的):
**你好,世界总司令**
更新:完整解决方案(固定前导空间)
GREEN = "\u001b[32;1m"
RESET = "\u001b[0m"
KEYWORD = "CommandGeek"
def color_word(*args):
colored = []
for a in args:
if isinstance(a, str):
colored.append(a.replace(KEYWORD, f"{GREEN}{KEYWORD}{RESET}"))
else:
colored.append(a)
return colored
print(*color_word('Hello', 1, 'World', True, '_CommandGeek_'))
def contains_word(*args):
for a in args:
if str(a).__contains__("CommandGeek"):
return True
return False
def color_message(*args):
if contains_word(*args): # unpack a tuple as multiple args (varargs)
# surround tuples with color-code and reset-code
colored = (f"{GREEN}{args[0]}",) + args[1:] # prepend to first element (new colored tuple)
colored = colored[0:-1] + (f"{colored[-1]}{RESET}",) # and append on last element (replace colored tuple)
return colored
return args
print(*color_message('Hello', 1, 'World', True, '_CommandGeek_'))
print(*color_message('Hello: CommandGeek'))支持ANSI的控制台上的打印-颜色:

进一步阅读
builtins (例如builtin.print() )。colorama或termcolor发布于 2022-02-01 16:44:32
在进行替换时,您将args设置为生成器表达式,因为您使用的是生成器表达式语法。args需要是一个tuple。您所要做的就是将单词tuple添加到语句的前面,它将运行得很好:
args = tuple(arg.replace('CommandGeek', f'{cg}CommandGeek{stop}') if isinstance(arg, str) else arg for arg in args)为了测试这一点,我做了:
cg = "_Testing_"
stop = "_123_"
_print = print
def print(*args, **kw):
#color the word "CommandGeek" green
args = tuple(arg.replace('CommandGeek', f'{cg}CommandGeek{stop}') if isinstance(arg, str) else arg for arg in args)
#Color entire the message green if "CommandGeek:" is in it.
if "CommandGeek:" in args:
args = cg + args + stop
_print(*args, **kw)
print('Test CommandGeek Test','CommandGeek','BlahBlah')输出:
Test _Testing_CommandGeek_123_ Test _Testing_CommandGeek_123_ BlahBlahhttps://stackoverflow.com/questions/70944139
复制相似问题