简体   繁体   English

如何在 python 中进行多次替换?

[英]How can I do the multiple replace in python?

As asked and answered in this post , I need to replace '[' with '[[]', and ']' with '[]]'.正如这篇文章中所问和回答的那样,我需要将 '[' 替换为 '[[]',并将 ']' 替换为 '[]]'。

I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser.我尝试使用 s.replace(),但由于它没有就地更改,我按如下方式运行以获取错误的 anwser。

path1 = "/Users/smcho/Desktop/bracket/[10,20]"
path2 = path1.replace('[','[[]')
path3 = path2.replace(']','[]]')
pathName = os.path.join(path3, "*.txt")
print pathName
-->
/Users/smcho/Desktop/bracket/[[[]]10,20[]]/*.txt
  • How can I do the multiple replace in python?如何在 python 中进行多次替换?
  • Or how can I replace '[' and ']' at the same time?或者我怎样才能同时替换'['和']'?
import re
path2 = re.sub(r'(\[|])', r'[\1]', path)

Explanation: 说明:

\\[|] will match a bracket (opening or closing). \\[|]将匹配括号(打开或关闭)。 Placing it in the parentheses will make it capture into a group. 将其放在括号中将使其成为一个组。 Then in the replacement string, \\1 will be substituted with the content of the group. 然后在替换字符串中, \\1将替换为组的内容。

I would use code like 我会使用像

path = "/Users/smcho/Desktop/bracket/[10,20]"
replacements = {"[": "[[]", "]": "[]]"}
new_path = "".join(replacements.get(c, c) for c in path)

还有这个通用的python多次替换配方: 单次传递多次替换

import re
path2 = re.sub(r'(\[|\])', r'[\1]', path1)

Or, to avoid regex, I would replace the opening bracket with a unique string, then replace the closing bracket and then replace the unique string - maybe a round about way, but to my mind it looks simpler - only a test would say if it is faster. 或者,为了避免正则表达式,我会用一个独特的字符串替换开始括号,然后替换结束括号,然后替换唯一的字符串 - 也许是一个圆形的方式,但在我看来它看起来更简单 - 只有一个测试会说如果它是比较快的。 Also, I'd tend to reuse the same name. 此外,我倾向于重复使用相同的名称。

ie

path1 = "/Users/smcho/Desktop/bracket/[10,20]"
path1 = path1.replace('[','*UNIQUE*')
path1 = path1.replace(']','[]]')
path1 = path1.replace('*UNIQUE*','[[]')

pathName = os.path.join(path1, "*.txt")

X = TE$%ST C@"DE X = TE$%ST C@"DE

specialChars = "@#$%&" specialChars = "@#$%&"

for specialChar in specialChars:对于 specialChars 中的 specialChar:

X = X.replace(specialChar, '')

Y = appname1.replace(" ", "") Y = appname1.replace(" ", "")

print(Y)打印(Y)

TESTCODE测试代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM