Bootstrap

python 从字符串中随机选取4个字符_如何随机更改字符串中的n个字符

如果您只想更改字符串中随机索引的不同字符,下面的函数将有所帮助。此脚本将要求输入字符串(即word)和需要用随机字符更改的总位置/索引((即)值或“n”位),并根据需要打印修改后的字符串。在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)

输出

^{pr2}$

;