Функция sub в regex может принимать функцию в качестве аргумента repl.
📄 Из документации:
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.
То есть для каждого совпадения будет вызвана функция для вычисления замены вместо замены на одну и ту же строку для всех совпадений.
Иными словами, для замены разных совпадений на разные строки не потребуется запускать re.sub() много раз для каждой строки замены. Достаточно определить функцию, которая вернёт строку для каждого из совпадений.
Описание слишком запутанное🤔, давайте лучше рассмотрим на простом примере:
Создаем карту замены. То есть какие строки на какие требуется менять.
remap = {
'раз': '1',
'два': '2',
'три': '3',
'четыре': '4',
'пять': '5',
}
Пишем функцию поиска строки для замены. Единственным аргументом будет объект re.Match.
Используя данные этого объекта мы вычисляем замену on-the-fly!
def get_str(match: re.Match):
word = match.group(1)
return remap.get(word.lower()) or word
Пример текста.
text = '''Раз Два Три Четыре Пять
Вместе будем мы считать
Пять Четыре Три Два Раз
Мы считать научим вас
'''
Теперь запускаем re.sub и вместо строки замены (repl) подаём имя функции.
(Данный паттерн ищет отдельные слова в тексте)
>>> print(re.sub(r'(\w+)', get_str, text))
1 2 3 4 5
Вместе будем мы считать
5 4 3 2 1
Мы считать научим вас
Думаю, достаточно наглядно 🤓
#libs#regex
🇺🇸#LosAngeles. Wild teens ransack Chevron store in Lincoln Heights in broad daylight.
Another SoCal store is taken over by rampaging teens racksacking aisles, grabbing whatever they can. This time, a Lincoln Heights Chevron station is hit. The frustrated store managers who want police to do more to stop the takeovers.
Follow us -> LiveLeak
Please do not curse the victims of the American fires. There are many innocent civilians and pro-Palestinian people. Those elites had already fled before the fires came.
#LosAngeles
This is absolutely disgusting and heartbreaking.
Homeless addicts on Skid Row in LA are using innocent dogs to test their drugs for fentanyl. These poor animals are being fed deadly substances, abused, neglected, sold for drugs, and thrown away like trash.
Volunteers from Starts With One Today are risking their lives to rescue these dogs with zero support from the city.
How has Mayor Karen Bass and LA leadership let this horror continue? Animals are suffering and dying in plain sight while officials do nothing.
This is pure cruelty. Where is the outrage? Where is the action?
#SaveSkidRowDogs#AnimalAbuse#LosAngeles
🔹👉🏻@SherriTenpenny
PERFECT RING FORMED OVER LOS ANGELES
This appeared high above L.A. just after dusk.
A bright linear trail stretched across the sky — and around it, a smooth circular arc expanded and held its shape.
The symmetry is what stands out.
A straight line through the center.
A clean curve wrapping around it.
It lingered long enough for people across the city to stop and stare.
Los Angeles, California.
Did you catch this from where you are?
MrMBB333
👇 Drop your city.
#MrMBB333#SkyWatch#LosAngeles
#Wildfires ravage #California, leaving 5 people dead and over 27,000 acres burned. #LosAngeles Authorities warned casualties may rise as the fires remain uncontained.
USA Major League Soccer🇺🇸
2026-04-19 23:00 UTC
Los Angeles FC vs. San Jose Earthquakes
Predicted outcome: Los Angeles FC❌
Predicted score: 2:1
Actual: San Jose Earthquakes 1:4
#LosAngeles#SanJoseEarthquakes
#Football#USAMLS
As #LosAngeles burns and #firefighters face a severe water crisis, criticism is mounting against #billionaires Stewart and Lynda #Resnick, whose $13B agricultural empire consumes more water than LA and SF combined.
#PalisadesWildFire
USA Major League Soccer🇺🇸
2026-05-10 20:30 UTC
New York City FC vs. Columbus Crew
Predicted outcome: New York City FC✅
Predicted score: 3:2
Actual: New York City FC 3:0
#NewYorkCity#ColumbusCrew
2026-05-10 23:00 UTC
Minnesota United FC vs. Austin
Predicted outcome: Minnesota United FC❌
Predicted score: 2:1
Actual: Draw 2:2
#MinnesotaUnited#Austin
2026-05-11 01:00 UTC
Los Angeles FC vs. Houston Dynamo
Predicted outcome: Los Angeles FC❌
Predicted score: 2:1
Actual: Houston Dynamo 1:4
#LosAngeles#HoustonDynamo
#Football#USAMLS