2

I already asked a question exactly like this, but the answer I got still worked and it used the .translate method within the function, but I want to use "for loops" to get the output I am looking for. Here is the link to the questions I asked a while ago: How can I replace multiple characters in a string using python?

I am having some trouble figuring out how to replace multiple characters in a string using a for loop. I am trying to write a functions called replace(string) that takes in an input, and replaces certain letters in the input with another letter.

Lets say I have the string "WXYZ" and I want to replace all the W with Y, X with Z, Y with W, and Z with X. I want it to do the replacement no matter what the input is. So if I also do something like replace("WWZXWWXYYZWYYY") it should replace the letters like I said above.

This is what I have done so far with the for loops:

def replace(string):
for letters in string:
    string = string.replace("W","Y").replace("X","Z").replace("Y","W").replace("Z","X")
print(string)

but when I run it with replace("WXYZ")

I get the output of the code as: WXWX

Instead of getting YZWX as the output. I also want to use the built in functions of python as well.

How can I achieve this?

  • 2
    You're looking for the **translate** method. – Prune Oct 05 '17 at 23:17
  • Literally a duplicate, same requirements, same try, same wording, same user... – adder Oct 05 '17 at 23:21
  • yeah, its the same one, but I need the functions to use "for loops" to get the output I am looking for. –  Oct 05 '17 at 23:21
  • I asked how to use the for loop in that post, but I was told to create another post asking the question to get the answer for the "for loops". –  Oct 05 '17 at 23:22
  • 1
    @Gin, Please edit your question and add a link to your previous one on this subject. You should also make it clear what is different about your new question. Otherwise you will be wasting a lot of people's time, which is not fair. – ekhumoro Oct 05 '17 at 23:33
  • 1
    @ekhumoro, I edited it the post, sorry about the confusion. –  Oct 06 '17 at 00:08
  • @Gin. Thanks. Did you see the [answer by Wiremu Jones](https://stackoverflow.com/a/46596201/984421)? I think it shows quite a good, simple way to solve your problem. – ekhumoro Oct 06 '17 at 00:43
  • Yeah, I saw it, thank you for your help in correcting my post! –  Oct 06 '17 at 00:53

3 Answers3

4

The problem is that you have intersection in your replaces. Python calls the methods from the left to right. That's why the following code works:

In [6]: 'ax'.replace('a', 'b').replace('b', 'g')
Out[6]: 'gx'

For getting ride of that problem you should replace the characters at once. One way around this is using regex or even better (if you just want to replace the character) the str.translate method:

In [16]: d = {"W": "Y", "X": "Z", "Y": "W", "Z": "X"}

In [17]: "WXYZ".translate(str.maketrans(d))
Out[17]: 'YZWX'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

The problem is that the third replace replaces also the new Ys (that were originally Ws).

One way is to use RegEx, as in here.

Another way I can think of is to swap into temporary values. But for that you need to find temporary values that would never appear in the original string.

For example, if you know the original string would be only UPPERCASE letters, you can use string.replace("W","y").replace("X","z").replace("Y","w").replace("Z","x"), and then replace all the lowercase back into uppercase without worrying about rereplacing the letters.

If you can't be sure it'll be only uppercase, find another set of chars that will never be on the string, or use RegEx.

Neo
  • 3,534
  • 2
  • 20
  • 32
1

Here is a solution to your problem. I hope this helps you :)

def replacer(string): #define the function with a parameter (which will be whatever string you want)
    newlist = [] #create a new list which will be the output
    strlist = list(string) #create a list of each character in the input string
    for item in strlist: #iterate through the items in the list of string characters
        if item == 'W': # this line and the next 7 lines check what the letter is and writes the letter you want to the new list
            newlist.append('Y')
        elif item == 'X':
            newlist.append('Z')
        elif item == 'Y':
            newlist.append('W') 
        elif item == 'Z':
            newlist.append('X')
    return ''.join(newlist) #output the new list as a string

replacer('WWZXWWXYYZWYYY') #call the function with the string as a parameter
Worm
  • 1,313
  • 2
  • 11
  • 28
  • Good effort. But you could just append to a string (i.e. `newstr += "Y"`) instead using list, and you don't need to copy the input string into a list, either (you can just iterate over it directly). – ekhumoro Oct 05 '17 at 23:40
  • Thanks @ekhumoro. I am not an advanced user so cheers for the feedback. It helps. – Worm Oct 05 '17 at 23:41
  • 1
    Thank you so much!!!! I wasted hours trying to figure out a good way. –  Oct 06 '17 at 00:52