简体   繁体   English

将字符串中的字符随机替换为当前字符以外的字符

[英]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:然后我在一个会随机替换n个字符的论坛上找到这个function:

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.这段代码做了我想要的,但有一个例外——它不考虑 string1 中与随机替换字符匹配的字符。 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.我知道问题出在我试图调整的 function 中,我在for循环下进行了预测,但我不确定要添加什么以防止替换字符等于 string1 中的旧字符。 All advice appreciated, if I'm overcomplicating things please educate me!感谢所有建议,如果我过于复杂,请教育我!

In the function you retrieved, replacing:在您检索到的 function 中,替换为:

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.它只是将 word[index](您要替换的字符)替换为 replacement_chars 字符串中的空字符串,有效地将其从替换字符中移除。

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!警告:如果 replacement_chars 只有 1 个字符,当原始字符与替换字符相同时,这两种方法都会失败!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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