Функция 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
🎟Get superpower with your Scores within Hybrid Savings—tons of tailored offers for Score holders and much more!
Hybrid Savings is a unique aggregator of exclusive deals that combines #WEB2 & #WEB3 in one convenient format of a Telegram Mini App. There you may find the best promotions, promo codes, and discounts!
🤔How can you access Hybrid Savings’ promo codes and other offers?
1) Visit Hybrid Savings via Partners or ScoreFront pages
2) Go to “Wallet” page
3) Click “Connect TON Wallet”
4) Enjoy exclusive deals!
💎 Now you can also enjoy all the ScoreFront benefits via Hybrid Savings right in the app—check the integration yourself using the button below!
🎟Yo dawg I herd u like benefits so we put a benefit in yo Score so u can be rewarded while u rewarded!Meet dozens of rewarding offers in Hybrid Savings offer on ScoreFront💎
Hybrid Savings is a unique aggregator of exclusive deals that combines #WEB2 & #WEB3 in one convenient format of a Telegram Mini App. There you may find the best promotions, promo codes, and discounts!
🤔How can you access Hybrid Savings’ promo codes and other offers?
1) Visit Hybrid Savings via Partners or ScoreFront pages
2) Go to “Wallet” page
3) Click “Connect TON Wallet”
4) Enjoy exclusive deals!
Explore the offer details and leverage you Score by accessing best deals using the button below!
While blockchain-based technologies have many qualities that set them apart from other computing paradigms, one of their primary value propositions is the generation of cryptographic truth.
Amidst the market uncertainty, cryptographic truth is taking on greater prominence in setting the stage for a new competitive battleground for #Web2 and #Web3 applications centered around the type of trust-minimized guarantees offered to users.
Now, it is up to users, developers, entrepreneurs, and forward-looking companies to begin building and adopting trust-minimized, quality protocols and products with real long-term viability.
As we continue to empower development, expansion and #innovation in this space, we recognise the importance of building a world powered by #truth.
This is the new standard.
Full read here.
[2 Feb-8 Feb] DWF Crypto Snapshot
Our latest #crypto report by our Managing Partner Andrei Grachev is up.
In this week's round up 💫
💠 Bitcoin #NFTs? It’s More Likely Than You Think
💠 Federal Rate Hikes Fuel #Bitcoin Price Sentiments
💠Renewed NFT Interest Drives #Trading And Lending On Popular #Marketplaces
💠History Comes To Life As Woodstock Takes To The #Metaverse
💠Western Financial Institutions Push #Crypto Prices With Spot Inflows
💠Japan Aims To Revitalize Its #Economy With Web3 #Innovation
💠Major #Web2 Companies Starts Hiring To Bolster #Web3 Capability
Full readhere.
Missed last week's snapshot? Read here.
Follow us on Medium here.
Stay up-to-date on the latest DWF Labs updates:
Website| Twitter | Linkedin | Telegram
🚀 Tria Integrates Aptos Network for Enhanced Global Transactions
Tria, a non-custodial financial operating system, has announced the integration of its global trading engine with the Aptos network. According to ChainCatcher, this integration allows over 500,000 users across more than 150 countries to directly access and trade Aptos assets. Users can now perform cross-chain exchanges and asset interactions within a single application without the need for cross-chain bridges.
The collaboration aims to leverage Aptos's sub-second confirmation and parallel execution technology to provide users with a seamless transaction experience. Additionally, it seeks to further connect traditional finance, Web2, and on-chain infrastructure.
#Tria#AptosNetwork#GlobalTransactions#NonCustodial#FinancialOperatingSystem#CrossChainExchanges#AssetInteractions#Blockchain#Web2#OnChainInfrastructure#Aptos#Crypto#DecentralizedFinance#Fintech#APT