Функция 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
🇮🇳🤝🇷🇺 Strengthening India–Russia Trade
On August 18, we hosted a business meeting at the Moscow Chamber of Commerce and Industry with the FICCI delegation.
✔ Bilateral trade has reached $67B — discussions at Innoprom 2025 aim to expand it to $100B.
✔ Opportunities for India in energy, manufacturing, agriculture, and textiles.
✔ Addressing the trade imbalance and exploring a Rouble–Rupee exchange mechanism.
Recently, I shared India’s perspective on RBK TV after the US imposed a 25% duty on Indian goods:
> “India, as the world’s 4th largest economy, has the right to protect its strategic sovereignty.”
A strong Indian business presence in Moscow reflects our shared commitment to deeper economic cooperation.
#IndiaRussia#Trade#FICCI#MCCI#SoltexGroup
🇷🇺🤝🇮🇳 INNOPROM 2025 Update
Today, I had the honor of speaking at the strategic session “Russia–India: Toward a $100 Billion Trade Turnover” at INNOPROM 2025 in Ekaterinburg.
Proud to share the stage with H.E. Vinay Kumar, Andrey Sobolev, Anil Agarwal, Nikita Ryblenkov, Igor Kurzhiyamsky, Mikhail Labudin, Badiga Shrikant, and Alexander Krutov.
Grateful for the opportunity to contribute to India–Russia trade dialogue as Deputy Chairman of MCCI’s India Commission & President of Soltex Group.
📍 I’m at INNOPROM till evening — happy to connect!
#INNOPROM2025#IndiaRussia#SoltexGroup#ManishKumar#TradeGrowth#EAEUIndia
🇷🇺🤝🇮🇳 I’m pleased to share that I will be participating as a speaker at INNOPROM 2025, Russia’s largest international industrial trade fair, taking place from July 7–10 at the Ekaterinburg-EXPO.
On July 7 (10:30–12:00, Hall 3.4), I will speak in the strategic session:
“Russia–India: Toward a $100 Billion Trade Turnover.”
As President of Soltex Group and Deputy Chairman of the MCCI Commission on Foreign Economic Relations with Partners in India, I look forward to contributing to the dialogue on expanding bilateral trade, addressing non-tariff barriers, and advancing the EAEU–India Free Trade Agreement.
INNOPROM is a premier global platform where industry, innovation, and international cooperation converge — bringing together decision-makers from around the world.
🔗 Register: expo.innoprom.com/registration/visitor-2025
🎟 Promo Code: ZVCZ2A (Free Entry)
Let’s build the next chapter of India–Russia industrial partnership.
#INNOPROM2025#SoltexGroup#ManishKumar#IndiaRussia#EAEUIndia#TradeGrowth
Sealing the Partnership in Moscow 🇮🇳🤝🇷🇺
We are pleased to witness a significant milestone in India-Russia relations, as EAM Dr. S. Jaishankar and Russia's Deputy Prime Minister Denis Manturov signed the Final Protocol after high-level talks in Moscow.
This development further strengthens bilateral cooperation, opening doors for trade, partnerships, and joint ventures across multiple sectors.
At Soltex Group, we view this as a promising step towards expanding our presence in Russia and fostering new opportunities for businesses.
📌 Interested in exploring business opportunities between India and Russia?
Connect with us — we’re here to support and guide you.
#IndiaRussia#TradeRelations#SoltexGroup#BusinessOpportunities#BilateralTrade#Partnership