问题描述
我无法获得以下内容的彩色输出:
Letters= ['QWERTYUPOIFSAJKVMPFOQWKFWSPAEOOIUSKFISPLCKSKLJHXIWTSLAVW']
data = (Letters)
from colorama import init
init()
init(convert=True)
from colorama import Fore
Selection1 = ['C','L','D','O','I']
Selection2 = ['K','W','Y']
Selection3 = ['N','V']
Selection4 = ['A','G','D']
for x in data:
if x in Selection1:
print (Fore.YELLOW,(x))
if x in Selection2:
print (Fore.GREEN,(x))
if x in Selection3:
print (Fore.LIGHTRED_EX,(x))
if x in Selection4:
print (Fore.BLUE,(x))
else:
print(Fore.WHITE,(x))
如果我将带有 [] 的列表中的字母更改为带有 () 的元组,则输出是彩色的,但我更愿意将所有字母作为一个列表放在一个块中,而不是单独打印在页面上。
解决方法
如果你想保持相同的类型,请:
>>> data = list(Letters[0])
要print
同一行中的所有字符,将''
传递给end
方法的print
参数:
>>> print(Fore.WHITE,x,end='')
此外,您的 if-else
块需要修复,因为您正在检查几乎所有条件,请参阅下面更新的代码,这样您将只为每个字符检查一次:
from colorama import init,Fore
init(convert=True)
Letters= ['QWERTYUPOIFSAJKVMPFOQWKFWSPAEOOIUSKFISPLCKSKLJHXIWTSLAVW']
data = list(Letters[0])
Selection1 = ['C','L','D','O','I']
Selection2 = ['K','W','Y']
Selection3 = ['N','V']
Selection4 = ['A','G','D']
for x in data:
if x in Selection1:
print(Fore.YELLOW,end='')
elif x in Selection2:
print(Fore.GREEN,end='')
elif x in Selection3:
print(Fore.LIGHTRED_EX,end='')
elif x in Selection4:
print(Fore.BLUE,end='')
else:
print(Fore.WHITE,end='')