[python] is it possible to add colors to python output?

so i made a small password strength tester for me, my friends and my family, as seen here:

import re strength = ['You didnt type anything','Terrible','weak sause','avarage','Good!','Very Strong', 'THE FORCE IS STRONG WITH THIS ONE'] score = 1 password=(raw_input("please type in the password you would like rated:"))  if len(password) < 1:       print strength[0] if len(password) >=1 and len(password)<=4:       print strength[1] else:     print ""  if len(password) >=7:     score+=1     print "password was made stronger by not being short" else:     print "Your password is really short, concider making it longer"  if len (password) >=10:     score+=1     print "password was made stronger by long" else:     print "An even longer password would make it stronger"  if re.search('[a-z]',password) and re.search('[A-Z]', password):     score+=1     print "password was made stronger by having upper & lower case letters" else:     print "Indlucing both upper and lower case letters will make your password stronger"  if re.search('[0-9]+', password):     score+=1     print "Password was made stronger by using numbers" else:     print "Using numbers will make your password stronger"  if re.search('[.,!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]',password):     score+=1     print "Password was made stronger by using punctuation marks and characters" else:     print "Using punctuation marks and characters will make the password stronger"  print "\n final password rating is:" print strength[score] 

what i was hoping to do is:

1st - add color to the comments i've given the user about the content of their password, good comments such as the: "password was made stronger by using numbers" will have a green output, while constructive feedback such as the "using numbers will make your password stronger" will have a red output, making it easier for the user to spot the pros and cons of his password

2nd - i was wondering, if it works the same, can i color certain items in my above "strength" list? making the first two red, the middle pair yellow and the last pair green?

ty!

This question is related to python colors

The answer is


IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.

You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle documentation just tells you the basics of using IDLE itself, and its idlelib library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.


Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)

Learning to read the termcap entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.

Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.

But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.


If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people


Questions with python tag:

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Upgrade to python 3.8 using conda Unable to allocate array with shape and data type How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip How to prevent Google Colab from disconnecting? "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? "E: Unable to locate package python-pip" on Ubuntu 18.04 Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' Jupyter Notebook not saving: '_xsrf' argument missing from post How to Install pip for python 3.7 on Ubuntu 18? Python: 'ModuleNotFoundError' when trying to import module from imported package OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website How to setup virtual environment for Python in VS Code? Pylint "unresolved import" error in Visual Studio Code Pandas Merging 101 Numpy, multiply array with scalar What is the meaning of "Failed building wheel for X" in pip install? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed Could not install packages due to an EnvironmentError: [Errno 13] OpenCV !_src.empty() in function 'cvtColor' error ConvergenceWarning: Liblinear failed to converge, increase the number of iterations How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How do I install opencv using pip? How do I install Python packages in Google's Colab? How do I use TensorFlow GPU? How to upgrade Python version to 3.7? How to resolve TypeError: can only concatenate str (not "int") to str How can I install a previous version of Python 3 in macOS using homebrew? Flask at first run: Do not use the development server in a production environment TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array What is the difference between Jupyter Notebook and JupyterLab? Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" How do I resolve a TesseractNotFoundError? Trying to merge 2 dataframes but get ValueError Authentication plugin 'caching_sha2_password' is not supported Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

Questions with colors tag:

is it possible to add colors to python output? How do I use hexadecimal color strings in Flutter? How do I change the font color in an html table? How do I print colored output with Python 3? Change bar plot colour in geom_bar with ggplot2 in r How can I color a UIImage in Swift? How to change text color and console color in code::blocks? Android lollipop change navigation bar color How to change status bar color to match app in Lollipop? [Android] How to change color of the back arrow in the new material theme? ng-change not working on a text input Getting individual colors from a color map in matplotlib Change button background color using swift language Change navbar text color Bootstrap Why cannot change checkbox color whatever I do? How to change link color (Bootstrap) Transparent ARGB hex value Named colors in matplotlib Android : change button text and background color How can I get the iOS 7 default blue color programmatically? Change tab bar tint color on iOS 7 How to set custom ActionBar color / style? set background color: Android how to convert rgb color to int in java Change text color with Javascript? How to change heatmap.2 color range in R? How can I invert color using CSS? Changing background color of text box input not working when empty Change color of bootstrap navbar on hover link? Javascript change color of text and background to input value Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS? Hex transparency in colors Change Text Color of Selected Option in a Select Box How to generate a number of most distinctive colors in R? Plot multiple lines (data series) each with unique color in R WPF Label Foreground Color Can I change the color of Font Awesome's icon color? Invert colors of an image in CSS or JavaScript Programmatically set TextBlock Foreground Color Change UITextField and UITextView Cursor / Caret Color How to add color to Github's README.md file Set a thin border using .css() in javascript How to color the Git console? How to change the link color in a specific class for a div CSS Set color of text in a Textbox/Label to Red and make it bold in asp.net C# What are the default color values for the Holo theme on Android 4.0? navbar color in Twitter Bootstrap How to change node.js's console font color? How to change default text color using custom theme? How to compare two colors for similarity/difference