Home > other >  How to format print statement with ANSI Escape Codes using variables?
How to format print statement with ANSI Escape Codes using variables?

Time:08-09

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")

CodePudding user response:

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
  • Related