简体   繁体   中英

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. 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.

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

#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']

Any ideas on how to make it work with colours?

Your problem isn't the colour; it's the if statement; you're comparing the item "\033[92m a" against "a" and those are not equal.

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())

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