New to both Python and StackOverflow, I'd like a little help. I'd like to print color in Python and have Googled but with little luck :( I've been confused each time and none has worked. This is the code I have typed.
answer = input ("Wanna go explore? OPTIONS : Yes or No")
if answer == "no":
print("Awww, come on, don't be like that, lets go!")
elif answer == "yes":
print ("Great! Lets go!")
else:
print("Whats that? I couldn't hear you!")
Now, I would like to have OPTIONS colored Green and Yes colored blue and No colored Red. How would one achieve this?
Method 1: Using ANSI ESCAPE CODE To add color and style to text, you should create a class called ANSI, and inside this class, declare the configurations about the text and color with code ANSI. Functions Used: background: allows background formatting. Accepts ANSI codes between 40 and 47, 100 and 107.
Go to Word > Preferences . Under Output and Sharing, select Print. Under Print Options, select the Print background colors and images check box. Close the Print dialog box, and go to File > Print.
to_rgb() function is used convert c (ie, color) to an RGB color. It converts the color name into a array of RGB encoded colors. It returns an RGB tuple of three floats from 0-1.
If you want to print color in the IDLE shell no answer using ASCI escape codes will help you as it does not implement this feature.
There is a hack specific to IDLE that lets you write to it's PyShell
object directly and specify text tags that IDLE has already defined such as "STRING"
which will appear as green by default.
import sys
try:
shell = sys.stdout.shell
except AttributeError:
raise RuntimeError("you must run this program in IDLE")
shell.write("Wanna go explore? ","KEYWORD")
shell.write("OPTIONS","STRING")
shell.write(" : ","KEYWORD")
shell.write("Yes","DEFINITION")
shell.write(" or ","KEYWORD")
shell.write("No","COMMENT")
answer = input()
When run in IDLE will result in this prompt:
Here is a list of all valid tags for use:
print("here are all the valid tags:\n")
valid_tags = ('SYNC', 'stdin', 'BUILTIN', 'STRING', 'console', 'COMMENT', 'stdout',
'TODO','stderr', 'hit', 'DEFINITION', 'KEYWORD', 'ERROR', 'sel')
for tag in valid_tags:
shell.write(tag+"\n",tag)
Note that 'sel'
is special that it represents the text that is selected, so it will be un-selected once something else is clicked on. As well it can be used to start some text selected for copying.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With