如何使用python替换字符串中的多个字符? [英] How can I replace multiple characters in a string using python?
问题描述
我在弄清楚如何替换字符串中的多个字符时遇到了一些麻烦.我正在尝试编写一个名为 replace(string) 的函数,它接受一个输入,并用另一个字母替换输入中的某些字母.>
假设我有字符串WXYZ",我想用 Y 替换所有 W,用 Z 替换 X,用 W 替换 Y,用 X 替换 Z.无论输入是什么,我都希望它进行替换.因此,如果我也执行诸如 replace("WWZXXWWXYYZWYYY") 之类的操作,它应该像我上面所说的那样替换字母.
这是我到目前为止所做的:
def 替换(字符串):对于字符串中的字母:string = string.replace("W","Y").replace("X","Z").replace("Y","W").replace("Z","X")打印(字符串)
但是当我用 replace("WXYZ") 运行它时
我得到的代码输出为:WXWX
而不是将 YZWX 作为输出.我也想使用 python 的内置函数.谁能帮我解决一下,谢谢!
请注意,您的调用的结构是将 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'
这篇关于如何使用python替换字符串中的多个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!