Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use for loop inside another for loop

I'm trying to print a file in rainbow colors. But however I have a problem, here is my code:

color = [91, 93, 92, 96, 94, 95]

with open(sys.argv[1]) as f:
for i in f.read():
    for c in color:
        print('\033[{0}m{1}\033[{0};m'
              .format(c, i), end='', flush=True)

The question is, I want the output like this: Hello(H in red, e in yellow, etc. ), but I got the output like this:HHHHHeeeeellll...(first H in red, second H in yello, etc.).

I know that because the first for will loop the second for. But how can I solve this?

like image 336
Remi Crystal Avatar asked Aug 16 '26 15:08

Remi Crystal


1 Answers

You don't want to loop over the colours for each letter just cycle through the colours, you can use itertools.cycle to cycle through the colors just calling next() to get the next color:

from itertools import cycle
color = cycle([91, 93, 92, 96, 94, 95])

with open(sys.argv[1]) as f:
    for i in f.read():
       print('\033[{0}m{1}\033[{0};m'
             .format(next(color), i), end='', flush=True)
like image 96
AChampion Avatar answered Aug 18 '26 06:08

AChampion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!