How to print colored text in Python?

前端 未结 30 3551
谎友^
谎友^ 2020-11-21 04:41

How can I output colored text to the terminal in Python?

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 05:19

    # Pure Python 3.x demo, 256 colors
    # Works with bash under Linux and MacOS
    
    fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
    bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"
    
    def print_six(row, format, end="\n"):
        for col in range(6):
            color = row*6 + col - 2
            if color>=0:
                text = "{:3d}".format(color)
                print (format(text,color), end=" ")
            else:
                print(end="    ")   # four spaces
        print(end=end)
    
    for row in range(0, 43):
        print_six(row, fg, " ")
        print_six(row, bg)
    
    # Simple usage: print(fg("text", 160))
    

    Try it online

提交回复
热议问题