How can I replace multiple characters in a string using python?

后端 未结 1 1448
[愿得一人]
[愿得一人] 2020-12-10 23:26

I am having some trouble figuring out how to replace multiple characters in a string.I am trying to write a functions called replace(string) that takes in an input, and repl

相关标签:
1条回答
  • 2020-12-11 00:21

    Note that your calls are structured in such a way that W is replaced with Y in the first call, and then Y is again replaced with W in the third call, undoing the first call's output.

    You should be using str.translate, it's much more efficient and robust than a bunch of chained replace calls:

    _tab = str.maketrans(dict(zip('WXYZ', 'YZWX')))
    def replace(string):
        return string.translate(_tab)
    

    >>> replace('WXYZ')
    'YZWX'
    >>> replace("WWZYWXXWYYZW")
    'YYXWYZZYWWXY'
    
    0 讨论(0)
提交回复
热议问题