How do I make a string split by every letter

Viewed 118

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

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('');
def split(word): 
  return [char for char in word]  
    
print(split('text'))
#['t', 'e', 'x', 't']

I think you need something like this a simple function. Your question is not really clear.

Use the list() wrapper:

print(list("text"))

Output:

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

partial output:

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 

P.S.

Looks like colors2 = colors + list(reversed(colors))[1:-1] might avoid doubling up the red red outputs when the cycle restarts on colors. That might require some careful testing.

And I stole cycle.

Related