1

I need help with coming up with a way to modify:

expr = expr.replace(ip,"("+ip+".~"+ip+")")

in

for ip in input:
    expr = expr.replace(ip,"("+ip+".~"+ip+")")

The problem I am facing is that all instances of ip get replaced. So if ip = "a1" then "a11","a12",....all are replaced with the expression "("+ip+".~"+ip+")"instead of just the element "a1". Here, expr is a string and ip is a list of strings.

What will be an efficient way to do this?

1
  • Please provide a sample snippet of input and the desired output. Commented Nov 25, 2015 at 1:11

1 Answer 1

1

You need to use word boundaries...

import re

expr = re.sub(r'\b' + ip + r'\b', "("+ip+".~"+ip+")", expr)
Sign up to request clarification or add additional context in comments.

3 Comments

What if re is unavailable because, say, that's an assignment?
re unavailable? how?
@Brian You should avoid shadowing standard lib modules in your code, however if it's unavoidable you can import re as something_else

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.