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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With