Search code examples
pythonnewlinenested-for-loop

append a new line in a nested for loop in Python


I want to change the color of the letters in a list of words. I use colorama library. Code:

from colorama import Fore
guess = ['great', 'hello', 'brave', 'stone']
li,ly = [],[]
for word in guess:
    for i in range(len(word)):
        if word[i] == 'b' or word[i] == 'a':
            color = Fore.RED
        elif word[i] == 's' or word[i] == 'e':
            color = Fore.GREEN
        else:
            color = Fore.BLACK
        letter = color + word[i] + Fore.RESET
        li.append(letter)
    result = ' '.join(li)
    ly.append(result)
print(*ly, sep = '\n')

Output is

g r e a t

g r e a t h e l l o

g r e a t h e l l o b r a v e

g r e a t h e l l o b r a v e s t o n e

Desired output would be

g r e a t

g r e a t

h e l l o

g r e a t

h e l l o 

b r a v e

g r e a t 

h e l l o 

b r a v e 

s t o n e

How do I add a new line in a nested for loop? I have not found a solution. Please help.


Solution

  • This should do it:

    guess = ['great', 'hello', 'brave', 'stone']
    color_letters = []
    spaced_words = []
    
    for word in guess:
        # insert spaces between letters
        for letter in ' '.join(word):
    
            # identify colour to apply
            if letter in 'ab':
                color = Fore.RED
            elif letter in 'es':
                color = Fore.GREEN
            else:
                color = Fore.BLACK
    
            # append to cumulative list of formatted letters
            color_letters.append(color + letter + Fore.RESET)
    
        # insert line breaks between words
        color_letters += '\n\n'
    
        # add / re-add cumulative list of letters to output list
        spaced_words.append(''.join(color_letters))
    
    print(''.join(spaced_words))