views:

134

answers:

4

As asked and answered in HERE, 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?
+8  A: 
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.

interjay
I was hoping to see this solution here :-). It is wise to avoid pointlessly splitting and rejoining strings, due to the potentially large number of unnecessary allocations this would cause.
SamB
+2  A: 

I would use code like

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

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")
neil