如何随机更改字符串中的n个字符

时间:2016-11-04 14:30:11

标签: python string python-3.x random

我想知道如何随机更改字符串中的n个字符,例如

orig = 'hello'

mod = 'halle'

我想在字符串中随机选择两个位置(orig[1]orig[4]),并用随机选择的字符替换原始字符串(hello)位置的字符(ae此处)会产生新的字符串halle

2 个答案:

答案 0 :(得分:1)

import random
import string
orig='hello'

char1=random.choice(string.ascii_lowercase)  #random character1
char2=random.choice(string.ascii_lowercase)  #random character2

while char1 == char2:                   # #check if both char are equal
    char2=random.choice(string.ascii_lowercase)

ran_pos1 = random.randint(0,len(orig)-1)  #random index1
ran_pos2 = random.randint(0,len(orig)-1)  #random index2

while ran_pos1 == ran_pos2:            #check if both pos are equal
    ran_pos2 = random.randint(0,len(orig)-1)

orig_list = list(orig)
orig_list[ran_pos1]=char1
orig_list[ran_pos2]=char2
mod = ''.join(orig_list)
print(mod)

答案 1 :(得分:0)

如果您只想在字符串中随机索引更改不同的字符,则以下功能将有所帮助。此脚本将要求输入字符串(即单词)以及需要随机字符更改的总位数/索引((即)值或“n”位置),这将根据需要打印修改后的字符串。 / p>

import random
import string

# Method to change N characters from a string with random characters.
def randomlyChangeNChar(word, value):
    length = len(word)
    word = list(word)
    # This will select the two 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(string.ascii_lowercase)
    # Finally print the string in the modified format.
    print("" . join(word))

# Get the string to be modified
string_to_modify = raw_input("Enter the string to be replaced...\n")

# get the number of places that needed to be randomly replaced
total_places = input("Enter the total places that needs to be modified...\n")

# Function to replace 'n' characters at random
randomlyChangeNChar(string_to_modify, total_places)

<强>输出

 Enter the string to be replaced...
 Hello
 Enter the total places that needs to be modified...
 3
 Hcado