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
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.
\[|]
\1
I would use code like
path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path)
python: Single pass multiple replace
import re path2 = re.sub(r'(\[|\])', r'[\1]', path1)
, , , , - , , , , - , . , .
.
path1 = "/Users/smcho/Desktop/bracket/[10,20]" path1 = path1.replace('[','*UNIQUE*') path1 = path1.replace(']','[]]') path1 = path1.replace('*UNIQUE*','[[]') pathName = os.path.join(path1, "*.txt")