[英]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.