简体   繁体   English

如何使用变量格式化带有 ANSI 转义码的打印语句?

[英]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.

相关问题 如何使用 function 使用 ANSI 代码格式化打印语句? - How to format print statement using ANSI Codes using function? 如何让 powershell 或 windows 终端使用 ANSI 转义码打印彩色文本? - How do I get powershell or windows terminal to print color text using ansi escape codes? 如何使用ansi转义码为python中的特定字符单元着色,其中字符单元格位置由变量确定 - How to colour a specific character cell in python using ansi escape codes where the character cell location is determined by variables 使用 ANSI 转义码 (Windows) 在 python 3.8 中更改控制台打印颜色 - Change console print color in python 3.8 with ANSI escape codes (Windows) Python使用ANSI转义码在终端上不再可见的行上打印 - Python print on lines that are not visible anymore on the terminal with ANSI escape codes 如何检测控制台是否支持Python中的ANSI转义码? - How to detect if the console does support ANSI escape codes in Python? 如何在不破坏ansi转义码的情况下替换字符串? - How to replace in string without breaking ansi escape codes? ANSI 转义码在 IDLE 上不起作用……(python) - ANSI escape codes not working on IDLE… (python) 在python中处理终端颜色代码(ANSI颜色转义代码) - Handling terminal colour codes ( ANSI colour escape codes ) in python 如何利用 input() 命令在 Python 中包含 ANSI 转义颜色代码? - How do I utilize the input() command to include ANSI escape color codes in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM