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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With