Suppose I have a string :
x="AAAABBABAABCCABBCA"
and I have the following information :
AAA=1
ABB= ignore/remove from final output
ABA=2
ABC=3
CAB=4
BCA= ignore/remove from final output
so when I translate x
the 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 it is giving me the wrong answer: 123CCA
I also tried:
def fun(x):
z=[]
for i 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 is something wrong with the syntax.
So the main problem is to check the string from the beginning and replace the characters. Please help me.
Thanks
Here's a solution that will properly print
1234
when run over your string :If a sequence of three characters doesn't do anything, there's not much point in having it check for it; just quietly continue on to the next one.
If you have your heart set on using
str.replace
to replace these strings within your code, you should look at the optional third parametercount
. If you limit it to a single replacement each loop, you should achieve your desired result.