python - create and insert randomly duplicates -
this not common question want create duplicates , insert randomly in string. following example.
i have file :
applestrawberrybananacitrusorange
and expected kind of output :
truspplestrawbeapplertrusrybananacitrusorangepple
in case program randomly select substring of length '4' : 'pple' , 'trus' , duplicates him 'twice(2)' before insertion.
i think run program using fonction copy copy.copy() , copy.insert() don't know how use randomly.
for moment;i write part of code read , write , else:
import copy chain='*' contain = '' file= raw_input ('filename:') x = open(file,'r') line in x: if not(chain in line): contain+=line e=copy.copy(contain[4:8]) f=copy.copy(contain[8:12]) y = open('copi','w') y.write(contain) y.write(f) x.close()
result:
applestrawberrybananacitrusorange awbe
as can see; doesn't work want. :(
thanks help
not sure if understand trying do.
you'll need library random selection:
import random
now here input string:
s = "applestrawberrybananacitrusorange" print s
you can use random.randint
select random position , extract 4-character word:
i = random.randint(0, len(s) - 4) w = s[i:i+4] print w
finally, can select 2 more random positions , insert word via string concatenation:
for j in range(2): = random.randint(0, len(s) - 4) s = s[:i] + w + s[i:] print s
output:
applestrawberrybananacitrusorange yban apybanplesybantrawberrybananacitrusorange
Comments
Post a Comment