How can I do the multiple replace in python?

Question:

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?
Asked By: prosseek

||

Answers:

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.

Answered By: interjay

I would use code like

path = "/Users/smcho/Desktop/bracket/[10,20]"
replacements = {"[": "[[]", "]": "[]]"}
new_path = "".join(replacements.get(c, c) for c in path)
Answered By: Mike Graham
import re
path2 = re.sub(r'([|])', r'[1]', path1)
Answered By: Will McCutchen

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")
Answered By: neil

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

Answered By: vikramsjn

X = TE$%ST [email protected]"DE

specialChars = "@#$%&"

for specialChar in specialChars:

X = X.replace(specialChar, '')

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

print(Y)

TESTCODE

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.