Reputation: 15
I want to have a program like the one below:
a = xy
b = a.replace("x", "y")
c = b.replace("y", "x")
print(c)
And I want the output to be "yx" but because the program is running the same string again the output is looking like "xx".
I hope you're getting my point.
Upvotes: 0
Views: 48
Reputation: 2819
According to your exemple:
c=a.replace("xy","yx")
Or for more general solution, if you are not looking for high time performance on big data volume, you can iterate:
c=[]
for i in range(0,len(a)-1,1):
if a[i]=="x":
c[i] ="y"
elif a[i]=="y" :
c[i] ="x"
else:
c[i] =a[i]
Upvotes: 0
Reputation: 707
I am not sure if I understood your question but maybe this could work:
a = 'xy'
letters = [char for char in a]
b = ''
for l in reversed(letters):
b += l
print(b)
And the final outcome isyx
.
Upvotes: 0
Reputation: 602
You have xy
you replace the x by y sou you have yy
Then you replace y by x so you get xx
You ca do:
A="xy"
B=a.replace("x","z")
C=B.replace("y","x")
D=C.replace("z","y")
print(D)
#yx
Upvotes: 0
Reputation: 10799
Instead of using str.replace
, you can make a translation table - which is really just a dict mapping the ordinal values:
>>> string = "hello world"
>>> translation_table = str.maketrans("el", "le")
>>> translation_table
{101: 108, 108: 101}
>>> string.translate(translation_table)
'hleeo wored'
>>>
Upvotes: 1