如何使用for循环替换字符串中的多个字符?

时间:2017-10-05 23:10:39

标签: python python-3.x

我已经问了一个完全相同的问题,但我得到的答案仍然有效,它在函数中使用了.translate方法,但是我想使用“for loops”来获取我正在寻找的输出。以下是我刚才提出的问题的链接:How can I replace multiple characters in a string using python?

我在查找如何使用for循环替换字符串中的多个字符时遇到了一些麻烦。我正在尝试编写一个名为replace(string)的函数,它接受一个输入,并用另一个字母替换输入中的某些字母。

假设我有字符串“WXYZ”,我想用Y替换所有W,用Z替换X,用W替换Z,用X替换Z.无论输入是什么,我都希望它进行替换。所以如果我也做像替换(“WWZXWWXYYZWYYY”)之类的东西,它应该替换我上面所说的字母。

到目前为止,这是我用for循环完成的:

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

但是当我使用replace(“WXYZ”)

运行它时

我得到代码的输出为:WXWX

而不是将YZWX作为输出。我也想使用python的内置函数。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:4)

问题是你的替换中有交集。 Python从左到右调用方法。这就是以下代码的工作原理:

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

为了解决这个问题,您应该立即更换字符。解决这个问题的一种方法是使用正则表达式甚至更好(如果你只想更换字符)str.translate方法:

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

In [17]: "WXYZ".translate(str.maketrans(d))
Out[17]: 'YZWX'

答案 1 :(得分:1)

问题在于,第三个replace也替换了新的Y s(最初为W s)。

一种方法是使用RegEx,如here中所示。

我能想到的另一种方法是换成临时值。但为此你需要找到永远不会出现在原始字符串中的临时值。

例如,如果您知道原始字符串只是大写字母,则可以使用string.replace("W","y").replace("X","z").replace("Y","w").replace("Z","x"),然后将所有小写字母替换回大写字母而不必担心重新放置字母。

如果您不能确定它只是大写,请找到另一组永远不会出现在字符串上的字符,或者使用RegEx。

答案 2 :(得分:1)

这是您的问题的解决方案。我希望这可以帮助你:)

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
相关问题