How can I do multiple replacements in python?

As asked and answered in this post , I need to replace '[' '[[]' and ']' with '[]]'.

I tried using s.replace (), but since it did not change in place, I ran as follows to get the 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 multiple replacements in python?
  • Or how can I replace '[' and '] at the same time?
+5
source share
5 answers
import re
path2 = re.sub(r'(\[|])', r'[\1]', path)

Explanation:

\[|]will match the parenthesis (open or close). Placing it in parentheses will lead to its capture in the group. Then in the replacement line \1will be replaced by the contents of the group.

+12
source

I would use code like

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

, , , , - , , , , - , . , .

.

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

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

All Articles