开发者

How can I do the multiple replace in python?

开发者 https://www.devze.com 2022-12-26 07:04 出处:网络
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.

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.

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?
  • 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.


I would use code like

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


There is also this generic python multiple replace recipe: Single pass multiple replace


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.

i.e.

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

specialChars = "@#$%&"

for specialChar in specialChars:

X = X.replace(specialChar, '')

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

print(Y)

TESTCODE

0

精彩评论

暂无评论...
验证码 换一张
取 消