Python replaces 3 random characters per line without duplicates

I need to change 3 random characters per line using Python, an example line:

Adriano Celentano 
Luca Valentina

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

It is necessary to deduce like this:

adraano cettntano
lacr vilenntina

I do not know where I can do this.

My code is:

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

If you just want to change characters that are not spaces, and not the same char in relation to the index, you can first print indexes in which non-white characters:

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

print(random.sample(inds,3))

Then use these 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 every time also replaced:

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))

exit:

Adoiano lelenhano
+2

. 3 , (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)

3 . while ,

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()
0

Source: https://habr.com/ru/post/1620597/


All Articles