AttributeError when trying to use Colorama (not a good title, I know)

1.8k Views Asked by At

I don't even know what to title this, as I don't know the terms. Basically, I have what I assume to be a beginner question, which I can't find an answer for. So, here's my code:

from colorama import Fore, Back, Style, init
init()
def colorprint(str1, str2):
    print(Fore.str2 + str1 + Fore.WHITE)
colorprint("words", "GREEN")

But, as expected, I can't use "str2" in "Fore.", as it's not one of the "options" (I guess) for it...

I get this error: AttributeError: 'AnsiFore' object has no attribute 'str2'

Sorry for not knowing how to label stuff... I don't know whether to call things functions, variables, objects, etc.

I'm using Python 3.

1

There are 1 best solutions below

0
Dekel On BEST ANSWER

The Fore object doesn't have the str2 attribute, but you can use the getattr function to get Fore.{GREEN}:

from colorama import Fore, Back, Style, init
init()
def colorprint(str1, str2):
    print(getattr(Fore, str2) + str1 + Fore.WHITE)
colorprint("words", "GREEN")