简体   繁体   中英

I need help changing the color of text in python

Hey I need help with coloring the text in a program I am making. It is a password program and I am trying to make the denied and granted red and green when they appear. Here is the program so far:

password = {"joseph":"jesus"}

print ("Welcome")
username = input("Please enter your username: ")
if username in password:
    print ("Granted.")
    mypassword = input ("Please enter your password: ")
    if mypassword == password[username]:
        print ("Granted.")
        answer = input("Do you like it? ")
        if answer == ("yes"):
            print ("I thought you would.")
        elif answer == ("no"):
            print ("I guess I could do better.")
        else:
            print ("Error!")
    else:
        print ("Denied!!!")
else:
    print ("Denied!!!")

input("Press enter to quit")

Python's standard input and output, as used by the input and print functions, is just plain text. It can output to an Unix terminal or Windows console, to a window in your IDE, or to a text file. And plain text doesn't have colors.

However, almost all modern-day terminals and consoles do have ways to do things like change colors. Almost all of them do so by using special control sequences—invisible text that means "switch to red" or "switch back to default color"—and there's a common subset of control sequences that most of them use.

If you want to learn about ANSI/VT100/etc. control sequences , and how to use termcap to dynamically look up the right sequences for almost any platform but Windows (on Windows you just assume ANSI), you can. But there's an easier solution: there are a zillion or so modules on PyPI that wrap it all up for you. I can't recommend which one of those zillion are the best, but the first one that came up in a search is ansicolors , which you can use like this:

>>> from colors import red, blue
>>> print('Some of these words are ' + red('red') + ' and ' + blue('blue'))
Some of these words are red and blue

But hopefully, on your console, the words "red" and "blue" will be colored appropriately, like this:

截屏

from termcolor import *
cprint('this text will be red','red')

This should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM