how to replace pairwise characters in a string using Python -
suppose have string :
x="aaaabbabaabccabbca"
and have following information :
aaa=1 abb= ignore/remove final output aba=2 abc=3 cab=4 bca= ignore/remove final output
so when translate x
output y
should be: y=1234
i tried:
def fun(x): x=x.replace("aaa","1") x=x.replace("aba","2") x=x.replace("abb","") x=x.replace("abc","3") x=x.replace("bca","") x=x.replace("cab","4") print x
but giving me wrong answer: 123cca
i tried:
def fun(x): z=[] in range(0,(len(x)+1)): if i=="aaa": i=i.replace("aaa",1) z.append(i) elif i=="aba": i=i.replace("aba",2) elif i=="abb": i=i.replace("abb","") elif i=="abc": i=i.replace("abc",3) elif i=="bca": i=i.replace("bca","") elif i=="cab": i=i.replace("cab","4") z.append(i) print ",".join(z)
but there wrong syntax.
so main problem check string beginning , replace characters. please me.
thanks
here's solution print 1234
when run on string :
x = "aaaabbabaabccabbca" newstr = '' in range(0,len(x),3): part = x[i:i + 3] if part == 'aaa': newstr += '1' elif part == 'aba': newstr += '2' elif part == 'abc': newstr += '3' elif part == 'cab': newstr += '4' print newstr
if sequence of 3 characters doesn't anything, there's not point in having check it; quietly continue on next one.
if have heart set on using str.replace
replace these strings within code, should @ optional third parameter count
. if limit single replacement each loop, should achieve desired result.
Comments
Post a Comment