How do I color a string in python terminal?

Question:

I am trying to color only a single variable in Python 3, however whenever I run the code, the sring gets colored in my terminal, but then everything else after that is colored too. I am trying to do it without any imports. Here’s my code.

tentativas = 20
print(f'Tentativas restantes:', f'33[0;36m {tentativas}')
Asked By: lnasser

||

Answers:

To reset the coloring you have to use "33[0;0m", either set it up as a prefix in your next print
e.g.

print("33[0;0m This is your next print")

Or perform an empty print just to reset the color

print("33[0;0m", end='')
Answered By: aleperno

You can use the module colorama

Install:
pip install colorama

Open script
from colorama import Force as color

Answered By: Mohammed Alissah

When using ANSI escape codes, e.g. 33[0;36m, best practice is to always reset the colour/style with 33[0;0m. Otherwise, the colour/style will spill over into subsequent messages in the terminal. Your example should then be:

tentativas = 20
print(f'Tentativas restantes:', f'33[0;36m {tentativas}33[0;0m')

If you don’t mind, allow me to refactor your code so it’s a little easier to read:

class Color():
  CYAN = '33[0;36m'
  OFF = '33[0;0m'

tentativas = 20

print(f'Tentativas restantes: {Color.CYAN}{tentativas}{Color.OFF}')

enter image description here

Though you don’t plan to use a Python package, you may want to consider making your code even easier to read. With Colorist (yes, I’m the author in full disclosure), your example could look like this:

from colorist import Color

tentativas = 20

print(f'Tentativas restantes: {Color.CYAN}{tentativas}{Color.OFF}')
Answered By: Jakob Bagterp