Функция 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
🎉 It Finally Happened: SEC Approves SPOT BTC-ETFs! 🚀
💡What This Means: SPOT BTC-ETFs let investors get into Bitcoin through more traditional investment avenues. This brings in more investors and makes the crypto market more like the traditional financial market.
🤝Join SLEX Exchange, catch the bull run wave, and trade Bitcoin to boost your earnings on the spot market!
#CryptoNews#SECBTCETF#Bitcoin#CryptoAdoption#FinancialMileston
Website| Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🚀 Polygon Stablecoin Supply Hits Record High of $3.6 Billion
The stablecoin supply on the Polygon network has reached a new peak, totaling $3.6 billion. According to NS3.AI, this milestone was confirmed by data from Artemis, indicating that the network has achieved an all-time high in stablecoin holdings. This development highlights the growing adoption and utilization of stablecoins within the Polygon ecosystem.
#Polygon#Stablecoin#Crypto#Blockchain#DeFi#Cryptocurrency#DigitalAssets#CryptoAdoption#CryptoNews#FinTech#POL
Bitcoin Rise and Market Liquidations
Bitcoin reaches $94,000, indicating market volatility. In 24 hours, $655 million liquidated from crypto assets. USDt-TON sees accelerated growth: over 1 billion issued and integrated with major exchanges. Telegram adoption boosts usage, making crypto accessible to 950 million users. Read more on market events and USDt-TON's progress through Watcher Guru and other sources.
#Bitcoin#Crypto#USDC#USDt-TON #TON#Telegram#WhaleAlert#MarketTrends#Liquidation#Blockchain#Stablecoin#Investing#Altcoins#VentureCapital#FinTech#Web3#DataAnalysis#CryptoAdoption
U.S. Must Lead in Crypto Regulation
U.S. Treasury Secretary Bessent emphasizes the need for the U.S. to take a global lead on cryptocurrency. Key points include bringing Bitcoin transactions onshore and ceasing government Bitcoin sales. Notably, the evolving regulatory landscape also aims to foster greater adoption of cryptocurrencies in the U.S.
#Crypto#U.S. #Bitcoin#Regulation#SEC#BTC#Blockchain#Innovation#CryptoAdoption#Finance#Bessent#Investment#CryptoPolicy#DigitalAssets#Mainstream#MarketTrends#Tech
Uniswap Expands Crypto-to-Fiat Options
Uniswap collaborates with Robinhood, MoonPay, and Transak to enable seamless crypto-to-fiat transactions. Users across 180+ countries can convert crypto and deposit funds directly into bank accounts via the mobile wallet. This feature will soon be available on the browser extension and web version. For more details, visit Leviathan News.
#Uniswap#Crypto#Robinhood#MoonPay#Transak#Banking#Fiat#DEX#Blockchain#Finance#Tech#Global#Innovation#Payments#Wallet#Transactions#Defi#Onboarding#CryptoAdoption#VC
🚀 Bitcoin Bancorp Expands Bitcoin ATM Network in Southern California
Bitcoin Bancorp has announced the launch of a licensed Bitcoin ATM network in Southern California, with the first machines now operational in the Los Angeles area. According to Odaily, this marks a new phase in the company's retail expansion in the United States, following its previous deployment in Texas, highlighting its strategy to accelerate growth in key markets.
Data indicates that the United States currently hosts over 35,000 Bitcoin ATMs, with the industry expected to grow from approximately $267 million in 2025 to $7.68 billion by 2034. California, with its large population, advanced tech ecosystem, and high rate of cryptocurrency adoption, is a significant growth market, ranking among the top states in the nation for ATM installations, second only to states like Texas.
#BitcoinBancorp#BitcoinATM#SouthernCalifornia#LosAngeles#RetailExpansion#Cryptocurrency#BitcoinMarket#CaliforniaTech#CryptoAdoption#USBitcoinATMs#ATMInstallations#BitcoinGrowth#BTC