循环遍历列表的 Colorama 工具 - 在终端Python中不起作用

问题描述

我无法获得以下内容彩色输出

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='')

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...