1

I have a text file that contains certain string sequences that I want to modify. For example, in the following string I would like to replace foo and bar each with a unique string (The new string will be based on what originally matches, so I won't know it before hand).

Original: foo text text bar text
Replaced: fooNew text text bar_replaced text

I am using regex to find the groups that I need to change based on how they are delimited in the actual text. If I just use re.findAll(), I no longer have the location of the words in the string to reconstruct the string after modifying the matched groups.

Is there a way to preserve the location of the words in the string while modifying each match separately?

4
  • Right after posting this I realized I could probably use str.replace() after re.findAll(), but since I have already typed it out I wonder if anyone has a better way. Commented Aug 4, 2017 at 14:39
  • is there a reason not to use re.sub? Commented Aug 4, 2017 at 14:39
  • If the search strings are hardcode strings and there is no context to account for when matching the strings, use chained replace methods. Commented Aug 4, 2017 at 14:41
  • @asongtoruin What I will substitute depends on what I find during matching. I can't know what to substitute ahead of time. Commented Aug 4, 2017 at 14:46

1 Answer 1

2

Option 1

I would recommend this for complicated scenarios. Here's a solution with re.sub and a lambda callback:

In [1]: re.sub('foo|bar', lambda x: 'fooNew' if x.group() == 'foo' else 'bar_replaced', text)
Out[1]: 'fooNew text text bar_replaced text'

Option 2

Much simpler, if you have hardcoded strings, the replacement is possible with str.replace:

In [2]: text.replace('foo', 'fooNew').replace('bar', 'bar_replaced')
Out[2]: 'fooNew text text bar_replaced text'
Sign up to request clarification or add additional context in comments.

2 Comments

In "Option 1" can any function go after lambda x: for the new replacement?
@digitaLink Exactly.

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.