Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

python - How do I make a string split by every letter

I want to make a program that makes text rainbow using termcolor but I don't know how to make string's into letters

Code:

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Actually, string is just like a letter list. You can just do like this:

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

If you want to color the letters in one string, try this:

# 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('');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...