GCS7
GCS7

Reputation: 47

Issue with modifying string with python

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?

Upvotes: 1

Views: 49

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You need to use word boundaries...

import re

expr = re.sub(r'\b' + ip + r'\b', "("+ip+".~"+ip+")", expr)

Upvotes: 1

Related Questions