简体   繁体   中英

Randomly Replacing Characters in String with Character Other than the Current Character

Suppose that I have a string that I would like to modify at random with a defined set of options from another string. First, I created my original string and the potential replacement characters:

string1 = "abcabcabc"
replacement_chars = "abc"

Then I found this function on a forum that will randomly replace n characters:

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)

This code does what I want with one exception -- it does not account for characters in string1 that match the random replacement character. I understand that the problem is in the function that I am trying to adapt, I predict under the for loop, but I am unsure what to add to prevent the substituting character from equaling the old character from string1. All advice appreciated, if I'm overcomplicating things please educate me!

In the function you retrieved, replacing:

word[index] = random.choice(replacement_chars)

with

word[index] = random.choice(replacement_chars.replace(word[index],'')

will do the job. It simply replaces word[index] (the char you want to replace) with an empty string in the replacement_chars string, effectively removing it from the replacement characters.

Another approach, that will predictably be less efficient on average, is to redraw until you get a different character from the original one:

that is, replacing:

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 replacement_chars only features 1 character, both methods would fail when the original character is the same as the replacement one!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM