'Replace Randomly Two Character in Python
I have a string
n = 'sophieMueller'
where I want to replace two random characters with two random ones of the following list:
replace = [
'X', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
]
Like this: s0phieM9eller
The following is almost working:
It gets a random indice of n (e. g. n[2] (p)) and replaces it with a random indice of list (e. g. replace[6] (5)).
n[randint(0, len(n))] = replace[randint(0, len(replace))]
print(''.join(n))
My only problem is that when I want to replace more then one character I sometimes get an error. I guess it's because they try to replace the same indice at the same time? Any solution to this?
n[randint(0, len(n))] = replace[randint(0, len(replace))]
n[randint(0, len(n))] = replace[randint(0, len(replace))]
Correct output for some runs and then:
Error:
Traceback (most recent call last):
File "/Users/x/Desktop/test.py", line 16, in <module>
n[randint(0, len(n))] = replace[randint(0, len(replace))]
IndexError: list index out of range
Solution 1:[1]
The issue is that randint(x, y) produces a random integer between x and y including both x and y.
List indices start at zero and end at len(list)-1. If randint happens to pick the largest possible number - either len(n) or len(replace) - it can't find the corresponding item in the list because the list ended one item before that.
The code you need is:
n[randint(0, len(n)-1)] = replace[randint(0, len(replace)-1)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TimO |
