简体   繁体   中英

Python replace 3 random characters in a string with no duplicates

I need change 3 random characters in a string using Python, example string:

Adriano Celentano 
Luca Valentina

I need to replace 3 characters, not replacing with the same character or number, not replacing space. How can I do this using Python ?

Need output like this :

adraano cettntano
lacr vilenntina

I don't know from where i can start to make this.

My code so far:

for i in xrange(4):
    for n in nume :
        print n.replace('$', random.choice(string.letters)).replace('#', random.choice(string.letters))

If you just want to change chars that are not whitespace and not the same char in regards to index, you can first pull the indexes where the non-whitespace chars are:

import random
inds = [i for i,_ in enumerate(s) if not s.isspace()]

print(random.sample(inds,3))

Then use those indexes to replace.

s = "Adriano Celentano"
import random
inds = [i for i,_ in enumerate(s) if not s.isspace()]
sam = random.sample(inds, 3)
from string import ascii_letters

lst = list(s)
for ind in sam:
    lst[ind] = random.choice(ascii_letters)

print("".join(lst))

If you want a unique char each time to replace with also:

s = "Adriano Celentano"
import random
from string import ascii_letters
inds = [i for i,_ in enumerate(s) if not s.isspace()]

sam = random.sample(inds, 3)

letts =  iter(random.sample(ascii_letters, 3))
lst = list(s)
for ind in sam:
    lst[ind] = next(letts)

print("".join(lst))

output:

Adoiano lelenhano

You can do this in two stages. In the first stage you pick 3 random positions in your string that meet your search criteria ( isalnum ):

import random
import string
replacement_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
# replacement_chars = string.letters + string.digits
input = 'Adriano Celentano'
input_list = list(input) 
input_dic = dict(enumerate(input_list))
valid_positions=[key for key in input_dic if input_dic[key].isalnum()]
random_positions=random.sample(valid_positions,3)

In the second part you generate 3 random characters and replace the characters in the previously selected positions. I have added a while loop to generate a new random character if it matches the existing value

random_chars = random.sample(replacement_chars,len(random_positions)) 
char_counter = 0
for position in random_positions:   
    #check if the replacement character matches the existing one
    #and generate another one if needed
    while input_list[position]==random_chars[char_counter]:
        random_chars[char_counter] = random.choice(replacement_chars)    
    input_list[position]=random_chars[char_counter]    
    char_counter = char_counter + 1
print "".join(input_list).lower()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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