Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 663
kingcope Avatar asked Dec 17 '15 15:12

kingcope


1 Answers

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
like image 83
Padraic Cunningham Avatar answered Sep 19 '22 16:09

Padraic Cunningham