pythonpython-3.xcolorscolor-codes

How to color an int variable in Python?


I am using Colorama to color strings in my code. Is there a way to color an int variable?, for example:

I want to color this part with a different color "~--( Round: 1 )--~". I tried to color the variable Rounds, so I convert it to a string, but It doesn't work.

Cards = 13
Rounds = 0
while Cards > 0:
   Rounds +=1
   RoundsColor = (Rounds, Fore.RED)
   print(Fore.BLUE+Back.WHITE+Style.BRIGHT + "*********************************************** ~--( Round:", RoundsColor, Fore.BLUE+Back.WHITE+Style.BRIGHT + ")--~ ***********************************************")

Solution

  • You want to use ANSI escape codes, I will let you take a look at https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 For example, if you want some text to be red and underlined, you do it this way :

    # For plain text
    print('\033[31;4m your text here \033[0m')
    # For variables
    print(f'\033[31;4m{var}\033[0m')
    
    

    I added extra spaces after 31m and before \033 but you don't need to add them. The idea is to surround your text or variable with escape code. \033[ let the interpreter know that you are going to use color code, after the [ you can place your color code, ALWAYS FOLLOWED by m. And don't forget to finish the color escape with \033[0m, with 0m acting as a reset value. If you forget to reset, your terminal will just keep on printing stuff with the color your defined with the escape code.