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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With