5

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?
2
  • Use regex to split on '[' or ']', then replace individual '[' and ']' with what you want, then join back. Commented Apr 12, 2010 at 16:16
  • google.com/… Commented Apr 12, 2010 at 16:18

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

I would use code like

path = "/Users/smcho/Desktop/bracket/[10,20]"
replacements = {"[": "[[]", "]": "[]]"}
new_path = "".join(replacements.get(c, c) for c in path)

Comments

1

There is also this generic python multiple replace recipe: Single pass multiple replace

Comments

0
import re
path2 = re.sub(r'(\[|\])', r'[\1]', path1)

Comments

0

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

Comments

0

X = TE$%ST C@"DE

specialChars = "@#$%&"

for specialChar in specialChars:

X = X.replace(specialChar, '')

Y = appname1.replace(" ", "")

print(Y)

TESTCODE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.