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

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -