[英]How to format print statement with ANSI Escape Codes using variables?
I know I can do print(f"\033[32m{newList[0]}\033[0m", f"\033[32m{newList[1]}\033[0m")
to print a list value in color,我知道我可以
print(f"\033[32m{newList[0]}\033[0m", f"\033[32m{newList[1]}\033[0m")
以彩色打印列表值,
But how would I make the 32m into a variable and make it work?但是我如何将 32m 变成一个变量并让它工作呢?
How would I make the 32m changeable with a variable?我将如何使用变量使 32m 可变?
Ex.前任。
dic = {
"greetings": ["hello", "bonjour"],
"goodbyes": ["adios", "4"]
}
newList = ["hola", "barev"]
dic.update({"greetings": newList})
color = 32
hola = dic["greetings"][0]
print(f"\033[", color, "m{newList[0]}\033[0m", f"\033[", color, "m{newList[1]}\033[0m")
Your own code works fine if you make all the strings in the print
function f-strings by appending an f
before the opening quote:如果您通过在开头引号前附加
f
来制作print
function f-strings中的所有字符串,您自己的代码就可以正常工作:
print(f"\033[", color, f"m{newList[0]}\033[0m", f"\033[", color, f"m{newList[1]}\033[0m")
Output: Output:
hola barev
Or just make it one long f-string:或者只是让它成为一个长的 f 字符串:
print(f"\033[{color}m{newList[0]}\033[0m\033[{color}m {newList[1]}\033[0m")
Output: Output:
hola barev
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.