简体   繁体   English

Python - 如何为列表中的文本着色?

[英]Python - how can I colour text in a list?

Maybe this is normal behaviour for using ANSI, but below I have a list of string variables.也许这是使用 ANSI 的正常行为,但下面我有一个字符串变量列表。 One of which I want a different colour.其中一个我想要不同的颜色。 If I try to use ANSI to change the colour of the string variable, it no longer recognizes it.如果我尝试使用 ANSI 更改字符串变量的颜色,它就不再识别它了。

a="\033[92m a"
#a="a"

list1 = [a, "b", "c", "d", "e"]
list2=[]

for i in list1:
    if i=="a":
        list2.append(i)

print(list2)

RESULT: []结果: []

Now if I get rid of the ANSI, it works现在,如果我去掉 ANSI,它就可以工作了

#a="\033[92m a"
a="a"

list1 = [a, "b", "c", "d", "e"]
list2=[]

for i in list1:
    if i=="a":
        list2.append(i)

print(list2)

RESULT: ['a']结果:['a']

Any ideas on how to make it work with colours?关于如何使其与颜色一起使用的任何想法?

Your problem isn't the colour;你的问题不是颜色; it's the if statement;这是if语句; you're comparing the item "\033[92m a" against "a" and those are not equal.您正在将项目"\033[92m a""a"进行比较,但它们不相等。

At a fundamental level, you're mixing business logic and presentation layer;从根本上讲,您正在混合业务逻辑和表示层; can you separate them?你能把它们分开吗?

Perhaps something like this:也许是这样的:

from dataclasses import dataclass

@dataclass
class Record:
    value: str
    emph: int

    def as_ansi(self):
        if self.emph:
            return f"\033[92m{self.value}\033[0m"
        else:
            return self.value

records = [
    Record('a', True),
    Record('b', False),
    Record('c', False),
]

for r in records:
    if r.value == "a":
        print(r.as_ansi())

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

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