Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color 'print' in Python

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)
like image 651
AliasSyed Avatar asked Nov 24 '25 17:11

AliasSyed


2 Answers

You can use f-strings:

print(f"{style.RED}{test1} {style.BLUE}{test2}{style.RESET}")
like image 165
Jonathan Ciapetti Avatar answered Nov 26 '25 06:11

Jonathan Ciapetti


If you don't mind, allow me to refactor your code to make it more pythonic and eventually more readable:

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

print(f"{Style.RED}ONE{Style.RESET}")
print(f"{Style.GREEN}TWO{Style.RESET}")

You can combine the strings like this:

red_text = f"{Style.RED}ONE{Style.RESET}"
green_text = f"{Style.GREEN}TWO{Style.RESET}"

print(f"{red_text} {green_text}")

F-strings were introduced in Python 3.6. If you're using an earlier version of Python, you can simply use string concatenation with a + between strings (instead of the less readable format() function):

print(Style.RED + "ONE" + Style.RESET)

red_text = Style.RED + "ONE" + Style.RESET

Instead of coding everything from scratch, you could also check other Python packages. For example Colorist – a lightweight package that enables you to add style and colour to text messages in the terminal (in full disclosure, I'm the author of this package). This may simplify your code:

from colorist import red, green

red("ONE")
green("TWO")

enter image description here

Another variation if you want to keep the f-strings. The output is the same:

from colorist import Color

print(f"{Color.RED}ONE{Color.OFF}")
print(f"{Color.GREEN}TWO{Color.OFF}")

Color cube

like image 27
Jakob Bagterp Avatar answered Nov 26 '25 05:11

Jakob Bagterp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!