0

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")
edwardvth
  • 41
  • 3

1 Answers1

0

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
GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16
  • Thanks, that works, but what about whenever I use a dictionary instead of a list? EX. `newdict = { "greetings": ["hello", "bonjour"], "goodbyes": ["adios", "4"] } newList = ["hola", "barev"] newdict.update({"greetings": newList}) color = [33, 32] hola = newdict["greetings"][0] def Test(): for i in range(3): print("|", f"\033[{color[0]}m{newdict["greetings"][1]}\033[0m", f"\033[{color[1]}m{newList[1]}\033[0m") Test()` – edwardvth Aug 08 '22 at 09:18
  • No problemo. The double quote in `newdict["greetings"][0]` terminates the string prematurely. So either change the double quotes in the square brackets to single quotes, or make the whole string a _triple quoted string_. So, respectively: `print("|", f"\033[{color[0]}m{newdict['greetings'][1]}\033[0m", f"\033[{color[1]}m {newList[1]}\033[0m")` and `print("|", f"""\033[{color[0]}m{newdict["greetings"][1]}\033[0m", f"\033[{color[1]}m {newList[1]}\033[0m""")`. Be sure to read [2.4.1. String and Bytes literals](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals). – GordonAitchJay Aug 08 '22 at 09:32
  • I have another question but it doesn't fit in the comments. I made a new question, can you please respond there? https://stackoverflow.com/questions/73284106/how-to-format-print-statement-using-ansi-codes-using-function – edwardvth Aug 08 '22 at 21:17