defarm
defarm

Reputation: 69

Is there a way to color individual elements in a list in Python?

I would like to color elements in a numpy.ndarray, specifically ones which are of numpy.int64 type.

For example, how do I color each 1 in the following list, say, red?

    L = [1,0,1,0,1]

I have tried using colorama. Here is my code. The result is also included.

from colorama import Fore, Back, Style

L = [i%2 for i in range(6)]

for i in L[::2]:
    L[i] = Fore.RED + str(i)

print(L)

['\x1b[31m1', '\x1b[31m0', '\x1b[31m1', '\x1b[31m0', '\x1b[31m1']

Upvotes: 0

Views: 4779

Answers (3)

parseltongue.io
parseltongue.io

Reputation: 1

Use the init() method and set autoreset to True.

from colorama import Fore, init
init(autoreset=True)

L = [i%2 for i in range(6)]
for i,x in enumerate(L):
    if x == 1: L[i] = Fore.RED + str(x)
    else: L[i] = str(x)

for x in L: print(x)

Upvotes: 0

Chrispresso
Chrispresso

Reputation: 4081

Lists don't have a concept of color. Colorama characters understood by your computer to represent values in different color. If you want to make your list print with certain colors you need to print each item in the list.

Let's say you want to make the 1's red:

for i in range(len(L)):
    if L[i] == 1:
        L[i] = Fore.RED + str(L[i]) + Fore.RESET
print(L)
# [0, '\x1b[31m1\x1b[39m', 0, '\x1b[31m1\x1b[39m', 0, '\x1b[31m1\x1b[39m']

print(', '.join(str(item) for item in L))  # Now prints certain items in red and others normal.

Upvotes: 2

user10340258
user10340258

Reputation: 359

As far I know we cannot store variables in list as colored variable. colorama only prints the variable in color. So your code will be

from colorama import Fore, Back, Style

L = [i%2 for i in range(6)]

for i in L[::2]:
    L[i] = str(i)

for item in L:print(Fore.RED+ str(item))
print(Style.RESET_ALL)

Upvotes: 0

Related Questions