Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?
like image 655
prosseek Avatar asked Apr 12 '10 16:04

prosseek


1 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.

like image 78
interjay Avatar answered Oct 04 '22 03:10

interjay