0

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.

AMC
  • 2,642
  • 7
  • 13
  • 35
Denis
  • 15
  • 2
  • Does this answer your question? [Best way to replace multiple characters in a string?](https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string) – AMC Apr 15 '20 at 21:11

4 Answers4

1

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'
>>> 
Paul M.
  • 10,481
  • 2
  • 9
  • 15
  • https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string – AMC Apr 15 '20 at 21:11
0

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
rafalou38
  • 576
  • 1
  • 5
  • 16
0

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.

csymvoul
  • 677
  • 3
  • 15
  • 30
0

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] 
Renaud
  • 2,709
  • 2
  • 9
  • 24