且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用python替换字符串中的多个字符?

更新时间:2023-02-12 18:43:44

请注意,您的调用的结构是将 W 替换为 Y 在第一个调用,然后在第三次调用中再次将 Y 替换为 W,撤消第一次调用的输出.

您应该使用 str.translate,它比一堆链接的 replace 调用更高效和健壮:

_tab = str.maketrans(dict(zip('WXYZ', 'YZWX')))定义替换(字符串):返回 string.translate(_tab)

>>>替换('WXYZ')'YZWX'>>>替换(WWZYWXXWYYZW")'YYXWYZZYWWXY'

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 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:

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. Can someone help me figure this out, thank you!

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'