简体   繁体   中英

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,

But how would I make the 32m into a variable and make it work?

How would I make the 32m changeable with a variable?

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:

print(f"\033[", color, f"m{newList[0]}\033[0m", f"\033[", color, f"m{newList[1]}\033[0m")

Output:

hola barev

Or just make it one long f-string:

print(f"\033[{color}m{newList[0]}\033[0m\033[{color}m {newList[1]}\033[0m")

Output:

hola barev

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM