Randomly replaces characters in a string with characters other than the current one
Let’s say I have a string and I want to modify it randomly with a set of options defined in another string. First, I created the original string and possible replacement characters:
string1 = "abcabcabc"
replacement_chars = "abc"
Then I found this feature to randomly replace n characters on the forum :
def randomlyChangeNChar(word, value):
length = len(word)
word = list(word)
# This will select the distinct index for us to replace
k = random.sample(range(0, length), value)
for index in k:
# This will replace the characters at the specified index with the generated characters
word[index] = random.choice(replacement_chars)
# Finally print the string in the modified format.
return "".join(word)
Except for an exception, this code does what I want — it doesn’t take into account characters in string1 that match random replacement characters. I know the problem is in the function I’m trying to tweak, I’m predicting under a for
loop, but I’m not sure what to add to prevent the replacement character from equaling the old character in string1. Thanks for all the advice, please educate me if I make things too complicated!
Solution
In the function you retrieved, replace :
word[index] = random.choice(replacement_chars)
with
word[index] = random.choice(replacement_chars.replace(word[index],'')
Will get the job done. It simply replaces word[index] (the character you want to replace) with an empty string in the replacement_chars string, effectively removing it from the replacement character.
Another method, which is expected to be less efficient on average, is to redraw until you get a different character than the original:
That is, replace:
word[index] = random.choice(replacement_chars)
with
char = word[index]
while char == word[index]:
char = random.choice(replacement_chars)
word[index] = char
or
while True:
char = random.choice(replacement_chars)
if char != word[index]:
word[index] = char
break
Warning: If the replacement_chars has only 1 character, both methods will fail when the original character is the same as the replacement character!