-1

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?

netrate
  • 423
  • 2
  • 8
  • 14
  • 1
    Does this answer your question? [How do I print colored text to the terminal?](https://stackoverflow.com/questions/287871/how-do-i-print-colored-text-to-the-terminal) – anarchy Oct 10 '22 at 02:08
  • Strings in Python have no notion of color. `"\033[92m a"` and `'a'` are just two different string. ANSI color sequences have sense only at the _output_ to terminal. – Yuri Ginsburg Oct 10 '22 at 02:14
  • 1
    Your problem isn't in the colour, it's in the `if` statement; you're comparing the item `"\033[92m a"` against `"a"` and those are not equal – Jiří Baum Oct 10 '22 at 02:33
  • this should sole yor comparison problem https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python – Joran Beasley Oct 10 '22 at 02:35
  • At a fundamental level, you're mixing business logic and presentation layer; can you separate them? – Jiří Baum Oct 10 '22 at 02:36
  • Yes I am realising that the ansi is presenting for the output, but it doesn't work to try to save the colours to a list. I have been wracking my brain to come up with a solution so that I can have a python LIST and each item is a separate colour. I am trying to work out a way to approach WORDLE with lists. – netrate Oct 14 '22 at 17:27

1 Answers1

0

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())
Jiří Baum
  • 6,697
  • 2
  • 17
  • 17
  • This is a bit past my learning level, but thank you. I am hoping to find something a bit more basic, if possible. I am looking for each new item in a list being a different colour when output. – netrate Oct 14 '22 at 17:29
  • How should the colour determined for each item? – Jiří Baum Oct 15 '22 at 09:09