I see I can color things using colorama
and termcolor
.
I'd like to color my numbers using Python formatters:
print("My value is %.2f" % value)
where the number is green if value > 0
otherwise red.
What's the most pythonic way to achieve this?
I don't believe there's anything you can easier/better that colorama or custom wrapper (take a look for this question for reference).
The reason is that python doesn't have great extensibility with string templates/formatting. Terminal output should be escape sequences, and there's no other way around, so you need to modify your output somehow.
One-timer with f-strings may me like:
print(f'Value is {OKGREEN if value > 0 else FAIL} {value}')
If your case allows this, perfect thing would be encapsulating logic to value class (roughly, if you can use subclass of int/float), so you can provide __format__
spec with support for coloring.
If you cant, you'll probably end up with wrapper around print.
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.