Замена подстроки с помощью регулярного выражения в python - PullRequest
0 голосов
/ 26 марта 2020

У меня есть следующая строка:

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.

Здесь я хочу заменить подстроки типа "(40 баррелей в день)" на"в среднем за день 40". Итак, в приведенной выше строке я хочу эти замены:

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

Как мне этого добиться?

1 Ответ

0 голосов
/ 26 марта 2020

Вы можете использовать re.sub() в вашей строке:

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

Код :

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...