简体   繁体   中英

Printing coloured text in Python not working. What am I doing wrong?

I am very new to Python, and wanted to learn how to print coloured text. I don't have any modules like termcolor or colorama, but I found that I can use ANSI escape sequences to do this.

I found a sample code:

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

However, when I run it, it just prints the entire thing like this:

[6;30;42mSuccess![0m

What am I doing wrong, and how can I print coloured texts?

Thank you very much!!

Edit: I am using python 3.7

So it turned out you were doing nothing wrong, just executing the Python code in an environment (the IDLE IDE on Mac) which does not recognize (by default?) ANSI escape sequences .

On Mac, ANSI escape sequences are supported, eg, by Terminal .

Try this

Blue =  '\033[34m' # Blue Text
print(Blue + 'Hello World')

at the spot where it says 34m that is the colour. red is 31 yellow is 33 purple is 35. and more. THis works for python

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