-1

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?

cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • 2
    There are 48 answers to [Print in terminal with colors](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors) - wich ones did you try out? – Patrick Artner Jan 28 '19 at 11:31
  • 1
    Duplicated Question [Print in terminal with colors?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors) – R. García Jan 28 '19 at 11:31
  • Hold on - that isn't right. I already know how to color things in terminal. This is a question about string formatters. – cjm2671 Jan 28 '19 at 11:34
  • Possible duplicate of [Print in terminal with colors?](https://stackoverflow.com/questions/287871/print-in-terminal-with-colors) – Maurice Meyer Jan 28 '19 at 11:36

1 Answers1

1

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.

Slam
  • 8,112
  • 1
  • 36
  • 44