Python 如何使字符串被每个字母分开

Python 如何使字符串被每个字母分开,python,string,termcolor,Python,String,Termcolor,我想做一个程序,使文本彩虹使用termcolor,但我不知道如何使字符串的字母 代码: 实际上,字符串就像一个字母列表。你可以这样做: string=“text” 对于字符串中的字母: 印刷品(信件) 如果要在一个字符串中为字母着色,请尝试以下操作: #确保库正常,我不知道,只需复制您的代码即可。 从termcolor导入彩色 #你自己填写所有字母的笔录 字母颜色={'a':'red','b':'blue','t':'yellow','e':'blue','x':'green'} string

我想做一个程序,使文本彩虹使用termcolor,但我不知道如何使字符串的字母

代码:


实际上,字符串就像一个字母列表。你可以这样做:

string=“text”
对于字符串中的字母:
印刷品(信件)
如果要在一个字符串中为字母着色,请尝试以下操作:

#确保库正常,我不知道,只需复制您的代码即可。
从termcolor导入彩色
#你自己填写所有字母的笔录
字母颜色={'a':'red','b':'blue','t':'yellow','e':'blue','x':'green'}
string=“text”
对于字符串中的字母:
打印(彩色(字母,字母颜色(字母)),结束=“”)
打印(“”);
我想你需要这样一个简单的函数。 您的问题不是很清楚。

使用
列表()
包装:

print(list("text"))
输出:

['t', 'e', 'x', 't']
部分输出: 附笔。 看起来
colors2=colors+list(反转(颜色))[1:-1]
可能会避免在循环重新启动时将红红输出加倍。这可能需要一些仔细的测试


我偷了。

谢谢,但我想改变每个字母的颜色,有没有办法?你是想用固定还是随机的方式给26个字母上色?你的问题是关于拆分的,你有几个答案,但在对这些答案的评论中,你说你要求的是颜色。请澄清你的问题。颜色?分裂?什么不起作用-粘贴错误消息或输出-在这种情况下,可能需要屏幕截图,而不仅仅是文本-您希望看到什么?欢迎加入。此外,您的
a.split
未分配给任何对象,因此基本上不执行任何操作<因此,代码>彩色(a..)适用于整个
a
变量,即“文本”。从解决这个问题开始。
print(list("text"))
['t', 'e', 'x', 't']
import itertools
import sys

def colored(ch, color):
    # fake function as I dont have termcolor
    sys.stdout.write(f"{ch}.{color} ")

def rainbow(a):

    colors = ['red', 'yellow','green','blue','magenta']

    #double it 1 2 3 => 1 2 3 2 1
    colors2 = colors + list(reversed(colors))[1:]

    #zip brings items of 2 lists together. cycle will just cycle through your
    #colors until a is done.  `a` itself is split merely by iterating over it 
    #with a for loop
    for ch, color in zip(a, itertools.cycle(colors2)):
        # print(f"{ch=} {color=}")
        colored(ch, color)

rainbow("text is long enough to cycle")
t.red e.yellow x.green t.blue  .magenta i.blue s.green  .yellow l.red o.red n.yellow g.green  .blue e.magenta n.blue o.green u.yellow g.red h.red  .yellow t.green o.blue  .magenta c.blue y.green c.yellow l.red e.red