vlad
vlad

Reputation: 49

Conditional string replacement

I need to replace a string depending on condition: I need to replace the variable term by the variable new_term on the variable string1 but only when we don't have "IS_ADDITIF{{" or "IS_FUN_ADDITIF{{" before.

Here is an example:

term = "DIGLYCERIDES"

new_term =  "IS_ADDITIF{{DIGLYCERIDES}},"

string1 : " FOOD ADDITIVES DIGLYCERIDES  (DIGLYCERIDES  IS_ADDITIF{{DIGLYCERIDES}}, IS_FUN_ADDITIF{{DIGLYCERIDES}}, DIGLYCERIDES     )"

newstring1= string1.replace(term, new_term)

The result is the following :

newstring1 = " FOOD ADDITIVES IS_ADDITIF{{DIGLYCERIDES}} (IS_ADDITIF{{DIGLYCERIDES}} IS_ADDITIF{{DIGLYCERIDES}}, IS_FUN_ADDITIF{{DIGLYCERIDES}}, IS_ADDITIF{{DIGLYCERIDES}} )"

Upvotes: 0

Views: 48

Answers (1)

ThePyGuy
ThePyGuy

Reputation: 18426

You can use regular expression with two subsequent negative lookbehind assertion, then replace the match using re.sub

>>> import re
>>> re.sub('(?<!IS_ADDITIF\{\{)(?<!IS_FUN_ADDITIF\{\{)'+term, new_term, string1)

' FOOD ADDITIVES IS_ADDITIF{{DIGLYCERIDES}},  (IS_ADDITIF{{DIGLYCERIDES}},  IS_ADDITIF{{DIGLYCERIDES}}, IS_FUN_ADDITIF{{DIGLYCERIDES}}, IS_ADDITIF{{DIGLYCERIDES}},     )'

Understanding the pattern: '(?<!IS_ADDITIF\{\{)(?<!IS_FUN_ADDITIF\{\{)'+term

(?<!IS_ADDITIF\{\{)       : String doesn't start with IS_ADDITIF{{
(?<!IS_FUN_ADDITIF\{\{)   : String doesn't start with IS_FUN_ADDITIF{{
term                      : Matching the value in term i.e. DIGLYCERIDES

Upvotes: 1

Related Questions