简体   繁体   中英

Python: printing in color and with style

If I want to print colored text, I would just do, using codes

green = '\033[0;32m'
print green + 'Hello'

and that gives me green text. If I want to have bold text, I would just use the code for bold, which is '\\033[1m'

Now, I tried to combine them as

print bold + green + 'Hello'

where bold is the aforementioned code, and that didn't work, gave me just green text with no bold style.

Anyway, what am I missing to combine color with style?

I can recommand this gist by Diego Navarro Mellén.

You can combine whatever you like when doing something like this:

with pretty_output(BOLD, FG_GREEN) as out:
    out.write('This is a bold text in green')

Following up on Or Duan's answer, turns out that the code I'm using for green works well alone but somehow when concatenated with another code does prevent the combination of styles.

In the reported Gist, the code for green text is

green = '\033[32m'

so lacks the 0; I have in mine. With this code, the concatenation achieves the result.

It's because the 0 in front is resetting, see here .

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