Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Colored text
#1
Question 
I've been looking on how to change your text in the command when you run python.
class Colors:
    RED = "\x1b[0;31;40"

def Starting():
    print(Colors.RED + "Hello")
    time.sleep(100)
This is my code that I thought would work to change my text red but it shows this.

←[0;31;40Hello

What am I doing wrong?
Reply
#2
Where did you get that code? I am used to seeing ansii color codes that look like this: \033[1;32m, \e[1;32m or \x1b[1;31m. I've never seen a code with two semicolons.

You can use the colorama module.
from colorama import Fore

print(Fore.RED + "This is red", Fore.GREEN + "This is green")
This is a bit easier to read than obscure escape sequences.
Reply
#3
You might take a look at the rich module. It handles a lot of the work for doing color effects.

>>> from rich.console import Console
>>> console = Console()
>>> console.print("Hello", style="red")
Hello
Reply
#4
This is what I use.
# SGR color constants
# rene-d 2018

class Colors:
    """ ANSI color codes """
    BLACK = "\033[0;30m"
    RED = "\033[0;31m"
    GREEN = "\033[0;32m"
    BROWN = "\033[0;33m"
    BLUE = "\033[0;34m"
    PURPLE = "\033[0;35m"
    CYAN = "\033[0;36m"
    LIGHT_GRAY = "\033[0;37m"
    DARK_GRAY = "\033[1;30m"
    LIGHT_RED = "\033[1;31m"
    LIGHT_GREEN = "\033[1;32m"
    YELLOW = "\033[1;33m"
    LIGHT_BLUE = "\033[1;34m"
    LIGHT_PURPLE = "\033[1;35m"
    LIGHT_CYAN = "\033[1;36m"
    LIGHT_WHITE = "\033[1;37m"
    BOLD = "\033[1m"
    FAINT = "\033[2m"
    ITALIC = "\033[3m"
    UNDERLINE = "\033[4m"
    BLINK = "\033[5m"
    NEGATIVE = "\033[7m"
    CROSSED = "\033[9m"
    END = "\033[0m"
    # cancel SGR codes if we don't write to a terminal
    if not __import__("sys").stdout.isatty():
        for _ in dir():
            if isinstance(_, str) and _[0] != "_":
                locals()[_] = ""
    else:
        # set Windows console in VT mode
        if __import__("platform").system() == "Windows":
            kernel32 = __import__("ctypes").windll.kernel32
            kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
            del kernel32


if __name__ == '__main__':
    for i in dir(Colors):
        if i[0:1] != "_" and i != "END":
            print("{:>16} {}".format(i, getattr(Colors, i) + i + Colors.END))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I classify colored images into 3 classes max22 0 687 Dec-04-2023, 10:33 PM
Last Post: max22
  fontforge Emoji encoding and colored glyphs pauf28 0 2,167 Dec-22-2020, 10:05 AM
Last Post: pauf28
  Error printing colored text julio2000 0 1,497 Feb-02-2020, 07:04 PM
Last Post: julio2000
  colored input() Trianne 6 18,611 Oct-15-2018, 07:50 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020