Lilly Lilly - 3 months ago 33
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
I do not know how to get e.g. 20% replacement.


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