Lilly Lilly - 27 days ago 13
Python Question

Python - Replace a given percentage (%) of characters (randomly) in a String?

I have a string e.g.

x = "aaaaaaaaaa"


I would like to replace e.g. 20% of the "a" with "b" . I tried:

x_new = ''.join(i if random.randint(0, 1) else 'b' for i in x)


but with
random.randint(0,1)
I do not know how to get e.g. 20% replacement.

Answer

The following code keeps the original a with probability 80%, otherwise, it replaces it with b

from random import random
x = "aaaaaaaaaa"
rand_replace = lambda c: c if random()>0.8 and c=='a' else 'b'
x_new = ''.join([rand_replace(c) for c in x])