简体   繁体   中英

Replacing substring using regex in python

I have a following string:

A cumulative 173,326 MMSCF of gas at
a daily average of 633 MMSCF and 10,974 barrels of condensate (40 barrels per day) were produced
from Mari Field during the period as against 164,108 MMSCF of gas at daily average of 597 MMSCF
and 15,507 barrels of condensate (56 barrels per day) for the corresponding period as per the
requirement / withdrawal of the customers.

Here I want to replace substrings like "(40 barrels per day)" with "at a daily average of 40". So in the above string, I want these replacements:

(40 barrels per day) -> at a daily average of 40
(56 barrels per day) -> at a daily average of 40

How can I achieve this?

You can use re.sub() on your string:

re.sub(r'\((\d+).*?\)', 'at a daily average of \\1', s)

Code :

import re

s = '''A cumulative 173,326 MMSCF of gas at
a daily average of 633 MMSCF and 10,974 barrels of condensate (40 barrels per day) were produced
from Mari Field during the period as against 164,108 MMSCF of gas at daily average of 597 MMSCF
and 15,507 barrels of condensate (56 barrels per day) for the corresponding period as per the
requirement / withdrawal of the customers.'''

result = re.sub(r'\((\d+).*?\)', 'at a daily average of \\1', s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM