简体   繁体   English

如何使用 Python 在终端中为数字着色?

[英]How can I colour numbers in terminal with Python?

I see I can color things using colorama and termcolor .我看到我可以使用coloramatermcolor事物termcolor

I'd like to color my numbers using Python formatters:我想使用 Python 格式化程序为我的数字着色:

print("My value is %.2f" % value)

where the number is green if value > 0 otherwise red.如果value > 0 ,则数字为绿色,否则为红色。

What's the most pythonic way to achieve this?实现这一目标的最pythonic方法是什么?

I don't believe there's anything you can easier/better that colorama or custom wrapper (take a look for this question for reference).我不相信有任何东西可以让您更轻松/更好地使用 colorama 或自定义包装器(请查看此问题以供参考)。

The reason is that python doesn't have great extensibility with string templates/formatting.原因是 python 对字符串模板/格式没有很好的可扩展性。 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:带有 f-strings 的一次性计时器可能我喜欢:

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.如果您的情况允许这样做,那么完美的做法是将逻辑封装到值类(粗略地说,如果您可以使用 int/float 的子类),那么您可以为__format__规范提供对着色的支持。

If you cant, you'll probably end up with wrapper around print.如果你不能,你可能最终会得到围绕打印的包装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM