【问题标题】:How can I use for loops to replace multiple characters in a string? [duplicate]如何使用 for 循环替换字符串中的多个字符? [复制]
【发布时间】:2017-10-05 23:10:39
【问题描述】:

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

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

假设我有字符串“WXYZ”,我想用 Y 替换所有 W,用 Z 替换 X,用 W 替换 Y,用 X 替换 Z。无论输入是什么,我都希望它进行替换。因此,如果我也执行 replace("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的内置函数。

我怎样才能做到这一点?

【问题讨论】:

  • 您正在寻找 translate 方法。
  • 字面意思是重复,相同的要求,相同的尝试,相同的措辞,相同的用户...
  • 是的,它是同一个,但我需要使用“for循环”的函数来获得我正在寻找的输出。
  • @Gin,请编辑您的问题并添加指向您之前关于此主题的问题的链接。你还应该清楚你的新问题有什么不同。否则你会浪费很多人的时间,这是不公平的。
  • @ekhumoro,我编辑了帖子,很抱歉造成混乱。

标签: python python-3.x


【解决方案1】:

问题是您的替换中有交集。 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'

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 辛苦了。但是您可以只附加到一个字符串(即newstr += "Y")而不是使用列表,并且您也不需要将输入字符串复制到一个列表中(您可以直接对其进行迭代)。
    • 谢谢@ekhumoro。我不是高级用户,所以为反馈欢呼。它有帮助。
    • 非常感谢!!!!我浪费了好几个小时试图找出一个好方法。
    【解决方案3】:

    问题是第三个replace 也替换了新的Ys(原来是Ws)。

    一种方法是使用正则表达式,如here。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-31
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      相关资源
      最近更新 更多