[Tutor] randomly generated error

Peter Otten __peter__ at web.de
Fri Jan 27 15:18:42 EST 2017


Freedom Peacemaker wrote:

> Hi,
> main idea was to :
> - get random characters word
> - randomly colour letters in my word
> - from this coloured word print all yellow letters
> 
> As it is random i need to be sure that at least one letter is yellow so i
> put yellow color into final variable. 

Why?

> This code works but randomly
> generates error. And i have no idea how solve this problem. Please help me
> 
> Traceback (most recent call last):
>   File "proj3", line 23, in <module>
>     w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y),
> colorpass))
>   File "proj3", line 23, in <genexpr>
>     w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y),
> colorpass))
> IndexError: string index out of range
> 
> This is my code:
> 
> from random import choice
> from string import ascii_letters, digits
> import re
> 
> chars = ascii_letters + digits
> 
> word = "".join([choice(chars) for i in range(10)])
> 
> R = '\033[31m'  # red
> G = '\033[32m'  # green
> B = '\033[34m'  # blue
> P = '\033[35m'  # purple
> Y = '\033[93m'  # yellow
> 
> colors = [R, G, B, P, Y]
> 
> colorpass = "\033[93m"
> for char in word:
>     colorpass += char + choice(colors)

The character is followed by the color-code sequence. If the last color is 
yellow re.end() == len(colorpos) which is not a valid index into the string.

> print(colorpass)
> 
> w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y),
> colorpass))
> print(w)
> 
> I am using Python 3.5.2 on Ubuntu 16.04

To print a colored character you have to put the color sequence before it, 
so I'd do just that. Here's an example without regular expressions:

word = "".join(choice(chars) for i in range(10))
colored_word = "".join(choice(colors) + c for c in word)
yellow_chars = "".join(part[0] for part in colored_word.split(Y)[1:])

print(word)
print(colored_word)
print("\033[0m", end="")
print(yellow_chars)

As we know that at least one character follows the color it is OK to write 
part[0] above. If that's not the case it's easy to avoid the exception by 
using part[:1] as that works for the empty string, too:

>>> "foo"[:1]
'f'
>>> ""[:1]
''




More information about the Tutor mailing list