我想制作一个程序,使用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'), colored(a, 'green'), colored(a, 'blue'), colored(a, 'magenta'),
colored(a, 'red'), colored(a, 'yellow'), colored(a, 'green'), colored(a, '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', '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
第页。S
看起来colors2 = colors + list(reversed(colors))[1:-1]
可能会避免在循环重新启动颜色时将红色输出加倍。这可能需要一些仔细的测试。
我偷了自行车。