Python - Replace a given percentage (%) of characters (randomly) in a String? -
i have string e.g.
x = "aaaaaaaaaa"
i replace e.g. 20% of "a" "b" . tried:
x_new = ''.join(i if random.randint(0, 1) else 'b' in x)
but random.randint(0,1)
not know how e.g. 20% replacement.
the following code keeps original a
character probability 80%, otherwise, replaces b
from random import random x = "aaaaaaaaaa" rand_replace = lambda c: c if random()<0.8 , c=='a' else 'b' x_new = ''.join([rand_replace(c) c in x])
and if want total probability of replacement 20% stringwise:
rand_replace = lambda c: c if random()<0.8**(1.0/len(x)) , c=='a' else 'b'
Comments
Post a Comment