Color 'print' in Python

Viewed 82

Been going thru this: How do I print colored text to the terminal?. My issue is little different than those solutions (or I just can't find it). I need to print two variables in different colors in same print statement.

For example print("{0} {1}".format(test1, test2)) Should print 'one' in RED and 'two' in BLUE.

Below works for single line. But how do I combine them.

os.system("")
class style():
  RED = '\033[31m'
  GREEN = '\033[32m'
  BLUE = '\033[34m'
  RESET = '\033[0m'

test1 = "ONE"
test2 = "TWO"

print(style.RED + "{0}".format(test1) + style.RESET)
print(style.GREEN + "{0}".format(test2) + style.RESET)
2 Answers

You can use f-strings:

print(f"{style.RED}{test1} {style.BLUE}{test2}{style.RESET}")

You could use the print statement's built in end parameter instead of os. This is how you would do it:

class style():    
    RED = '\033[31m'
    GREEN = '\033[32m'
    BLUE = '\033[34m'
    RESET = '\033[0m'

test1 = "ONE"
test2 = "TWO"

print(style.RED + "{0}".format(test1) + style.RESET, end='')
print(style.GREEN + "{0}".format(test2) + style.RESET, end='')

And no, I don't think you can combine them.

Another thing. Your class notation is not good. Normally, you should use the init function to initialize your variables.

In this case, a class is a bad idea to store those strings. I think you should define those as variables instead of in a class, like follows:

RED = '\033[31m'
GREEN = '\033[32m'
BLUE = '\033[34m'
RESET = '\033[0m'

test1 = "ONE"
test2 = "TWO"

print(RED + "{0}".format(test1) + RESET, end='')
print(GREEN + "{0}".format(test2) + RESET, end='')
Related