Lilly Lilly - 1 year ago 74
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.

Answer Source

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])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download