Tim
Tim

Reputation: 99606

Search and replace some text in strings in Python?

I would like to search in a text of multiple lines to see if each line has sentence=" followed by some text and ended with " />'. If yes, see if the text between sentence=" and " />' has ", if yes, replace it with '. For example, one such line is:

<number="4" word="start" sentence="I said, "start!"" />

I would like to change it to be

<number="4" word="start" sentence="I said, 'start!'" />

Note that such cases can happen more than once in each single line of the text.

I wonder how to use regex in Python to accomplish that? Thanks!

Upvotes: 4

Views: 101

Answers (1)

roippi
roippi

Reputation: 25974

You can provide a callable to re.sub to tell it what to replace the match object with:

s = """<number="4" word="start" sentence="I said, "start!"" />"""

re.sub(r'(?<=sentence=")(.*)(?=" />)', lambda m: m.group().replace('"',"'"), s)
Out[179]: '<number="4" word="start" sentence="I said, \'start!\'" />'

Upvotes: 3

Related Questions