如何让每个字母分割一个字符串 部分输出:附注

问题描述

我想制作一个使用termcolor制作文字彩虹的程序,但我不知道如何将字符串变成字母

代码

from termcolor import colored

def rainbow(a):
    alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

    a.split(str(alphabet))

    print(colored(a,'red'),colored(a,'yellow'),'green'),'blue'),'magenta'),'blue'))

rainbow("text")

解决方法

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

string="text"
for letter in string:
    print(letter)

如果你想给一个字符串中的字母上色,试试这个:

# Make sure the library is OK,I don't know it,just copy your code.
from termcolor import colored

# fill the dict for all letters yourself
lettercolors = {'a':'red','b':'blue','t':'yellow','e':'blue','x':'green'}
string="text"
for letter in string:
    print(colored(letter,lettercolors(letter)),end='')
print('');
,
def split(word): 
  return [char for char in word]  
    
print(split('text'))
#['t','e','x','t']

我认为你需要这样一个简单的函数。 你的问题不是很清楚。

,

使用 list() 包装器:

print(list("text"))

输出:

['t','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 

附注

看起来 colors2 = colors + list(reversed(colors))[1:-1] 可能会避免在颜色循环重新开始时将 red red 输出加倍。这可能需要一些仔细的测试。

我偷了cycle