繁体   English   中英

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

[英]Randomly Replacing Characters in String with Character Other than the Current Character

假设我有一个字符串,我想用另一个字符串中的一组定义的选项随机修改它。 首先,我创建了原始字符串和可能的替换字符:

string1 = "abcabcabc"
replacement_chars = "abc"

然后我在一个会随机替换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)

这段代码做了我想要的,但有一个例外——它不考虑 string1 中与随机替换字符匹配的字符。 我知道问题出在我试图调整的 function 中,我在for循环下进行了预测,但我不确定要添加什么以防止替换字符等于 string1 中的旧字符。 感谢所有建议,如果我过于复杂,请教育我!

在您检索到的 function 中,替换为:

word[index] = random.choice(replacement_chars)

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

会做的工作。 它只是将 word[index](您要替换的字符)替换为 replacement_chars 字符串中的空字符串,有效地将其从替换字符中移除。

另一种方法,预计平均效率较低,是重新绘制,直到您获得与原始字符不同的字符:

也就是说,替换:

word[index] = random.choice(replacement_chars)

char = word[index]
while char == word[index]:
    char = random.choice(replacement_chars)
word[index] = char

或者

while True:
    char = random.choice(replacement_chars)
    if char != word[index]:
        word[index] = char
        break

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

暂无
暂无

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

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