尝试使用Colorama时出现AttributeError(我知道这不是一个好标题)

2024-03-28 16:44:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我甚至不知道该怎么称呼它,因为我不知道术语。基本上,我有一个我认为是初学者的问题,我找不到答案。所以,我的代码是:

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

但是,正如所料,我不能在“Fore”中使用“str2”,因为它不是“选项”(我猜)之一。。。在

我得到这个错误: AttributeError: 'AnsiFore' object has no attribute 'str2'

很抱歉不知道怎么给东西贴标签。。。我不知道是否应该称事物为函数、变量、对象等

我用的是python3。在


Tags: 答案代码fromimportinitstyledefback
1条回答
网友
1楼 · 发布于 2024-03-28 16:44:13

Fore对象没有str2属性,但是可以使用^{} function来获得{}:

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

相关问题 更多 >