Функция 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
C U R V E S / Under Magnitude by Marc Fornes / THEVERYMANY
The strength of #undermagnitude is achieved by 'Intensive Curvature,' which is the maximization of double #curvature across the project while constraining maximum radii. The result is a #structure that has much tighter curvature with constant change of direction, and results in more structurally performance. 'Intensive Curvature' leads to the curly, tubular branching characteristics consistent across the studio's body of work.
In order to achieve structural #stability , each stripe assumes high degrees of curvature individually and high degrees of double curvature in accumulation -- amounting to extreme structural #rigidity throughout the project.
#arch_shovel#archdaily
🚀 Iranian Parliament Speaker Warns of Consequences for Ceasefire Violations
On April 9, Iranian Parliament Speaker Mohammad Bagher Ghalibaf stated that any breach of the ceasefire agreement will result in clear consequences. According to BlockBeats, Ghalibaf emphasized the importance of adhering to the terms of the agreement to avoid potential repercussions. The statement underscores the significance of maintaining peace and stability in the region.
#Iran#Parliament#Ceasefire#Consequences#Peace#Stability#MiddleEast
🚀 Canada's March Unemployment Rate Matches Previous Value at 6.7%
Canada's unemployment rate for March was reported at 6.7%, according to Jin10. This figure aligns with the previous month's rate and is slightly better than the anticipated 6.80%. The data suggests stability in the Canadian labor market during this period.
#Canada#unemploymentrate#March2026#labor market #stability#Jin10
🚀 Bitcoin's Stability Amid Institutional Buying and Whale Selling
Bitcoin has maintained a price range between $65,000 and $73,000 over the past six weeks. According to NS3.AI, this stability is due to institutional buying counterbalancing selling activities from whales, miners, medium-sized holders, and Bhutan. U.S. spot ETFs have absorbed approximately 50,000 BTC monthly. Meanwhile, miners have sold over 19,000 BTC in the past week, and whale holdings have shifted from an annual accumulation of 200,000 BTC to a reduction of 188,000 BTC.
#Bitcoin#Stability#InstitutionalBuying#WhaleSelling#NS3AI#USSpotETFs#BTC#Miners#WhaleHoldings#PriceRange#Crypto
🚀 Finland to Restrict Nuclear Weapons Deployment During Peacetime
Finland has announced plans to declare its intention not to station nuclear weapons on its territory during peacetime, despite ongoing legislative changes that would permit such a deployment. Bloomberg posted on X, highlighting Finland's strategic decision amid evolving security dynamics in the Nordic region. The move comes as Finland reassesses its defense policies in response to regional security concerns. The country's government is working on legal amendments that would enable the deployment of nuclear weapons if deemed necessary in the future. However, Finland remains committed to maintaining a nuclear-free stance during times of peace, reflecting its cautious approach to national security. This decision aligns with Finland's broader defense strategy, which prioritizes stability and peace in the region. The legislative changes are part of Finland's efforts to enhance its defense capabilities while ensuring transparency and adherence to international norms. Finland's stance on nuclear weapons deployment underscores its commitment to regional security and diplomatic engagement.
#Finland#NuclearWeapons#Peacetime#DefensePolicy#RegionalSecurity#NordicRegion#NationalSecurity#Diplomacy#LegislativeChanges#NuclearFree#InternationalNorms#Stability
Bay Harbor Re Secures $50M Funding
Bay Harbor Re, a reinsurance firm, has announced a funding round of $50 million, set for December 13, 2024. The company focuses on delivering stability and protection tailored to meet the specific needs of its partners.
#Reinsurance#Funding#Investment#BayHarborRe#FinancialServices#Insurance#Stability#Protection#Partners#BusinessDevelopment#MarketInsights#RiskManagement#Capital #2024 #Profitability#Growth#InsuranceMarket#CorporateNews#FundingRound
Market Trends Impact Developer Salaries
Developers face salary stagnation as the job market grows competitive. With more candidates than job openings, mid-senior professionals find job switches yield minimal salary increases. Becoming a tech lead is rare and corporations limit hiring senior candidates. Stability may lie in entrepreneurship or pet projects instead. Consider exploring these options for long-term financial health.
#JobMarket#DeveloperSalaries#Entrepreneurship#PetProject#IT#CareerGrowth#TechIndustry#EmploymentTrends#SalaryTrends#BusinessModel#Stability#Competition#JobSwitch#MidCareer#SeniorDevelopers#MarketAnalysis#ITCareers#FinancialPlanning#TechJobs#Startup#TechLeadership