Функция 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
🆓REDEEM CODES🆓
🎁🔗#Genshin #Code This WeekNEW!!
A new code introduced to Genshin:
🎈A0NBWRZZI3XJ🎈
✨20 primogems and 160 geodes of replication
Genshin Impact v6.5 Codes (Full List)
Add @APKFreeDownloader_Bot to get any apk you want.
🆓REDEEM CODES🆓
🚀💎Genshin Impact 6️⃣.3️⃣#Code
🌟📌The 6.3 version "Luna IV" update is finally arrived, with a new version launch code for all players:
🌙【 MoonInvitationLunaIV 】🌙NEW!!
Enter it in the code redemption box and you'll receive 40 primogems, 20 thousand mora, and 3 hero's wit!
🕹️Join Columbina in Genshin Impact 6.3
🎁#Genshin Impact New Codes (Complete List)
Add @APKFreeDownloader_Bot to get any apk you want.
🆓REDEEM CODES🆓
🏰Cookie Run Kingdom 6️⃣.1️⃣🎁#Code
🍪🚩November 2025
✨🍪Redeem Code: 【 HOTY2025 】
Redeem it and you'll receive:
✅💎3k Crystals
✅🌈1.5k Rainbow cubes
✅🍪1k Choco Chalks
🔎🎁#CRK Codes: All the Latest Codes & How To Redeem
Add @APKFreeDownloader_Bot to get any apk you want.
🆓REDEEM CODES🆓
#🐉🕹️Dragon Raja : ReRise🎁#Code
🎉📍SEA Server Opens on 8/14!!
6GB+ Free Space Is Required!!⬇️
Launch Code: 🎁【 LZHX66】🎁
(The code can be redeemed on 8/14 at 10 AM)
Use this EXCLUSIVE code to get 1x Starter Pack of 20x Chalice Supply Box.
⌛ Code can EXPIRE FAST‼️ Claim it AS SOON AS you see this!
[MORE REWARDS]
*Launch to get 🎡400 DRAWS!!
*Complete the Dragon Raja × Life Makeover Collaboration Event for an additional 💎500 DIAMOND rewards!
About 🎮Dragon Raja : ReRise]
[Customization] Design Your INKMANCER in Casual/Retro/Street/Futuristic style.
[Time Combat] PvE Training. PVP Duels. Club Matches.
[Life Sim] Romantic Relationship. Motorbike City Tour. Party Fun.
[Narrative] Immersive NPC Interactions.
Add @APKFreeDownloader_Bot to get any apk you want.
🆓REDEEM CODES🆓
🎁🕵️YuYu Hakusho:Slugfest Gift Codes
Redemption Begins 🎉on 7/23, at 7 PM (GMT+8)!!🔥✨
Use the exclusive codes below after the official release for amazing launch gifts: 200x Crystal Bead 💎, 20,000x Currency💰, 10x Omamori Enhancer🔮, and 1x Intermediate Enhancer🔮.
🎁#CODE 1:【 apkpure0723 】 (US Server)
🎁#CODE 2:【 apkpure2507 】 (US Server)
📍Pre-download begins on 7/22, at 6 PM (GMT+8)!
🕹Pre-register Now!!!
About YuYu Hakusho:Slugfest
Play as Yusuke (a young spirit detector) to track down and eliminate all evil demons and their human helpers and safeguard the human world from supernatural threats.
Add @APKFreeDownloader_Bot to get any apk you want.
#code
To me, high cognitive load reduces my code quality. In thoery, there are many tricks to reduce cognitive load, e.g., better modularity. In practice, they are not always carried out. Will chatGPT help? Let’s see.
https://www.caitlinhudon.com/posts/programming-beyond-cognitive-limitations-with-ai
Internet do'kon qilishda eng ko'p kerak bo'ladigan fungsiyalardan biri. Narxlarni foydalanuvchiga formatlab ko'rsatish fungsiyasi
const formatPrice = (price) => {
return price?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
};
#code
☑️@valisherbotirov
🆓REDEEM CODES🆓
#Genshin Impact ✨October New #Code
👀Last Check: ⏳10/30!!!
Enter the Genshin Impact latest code 🎁【 GS61RD26W966 】🎁 for 20,000 moras✨🎁 and TONS MORE!!!
Genshin Impact October Codes: (All Active Codes!!)
👉【 MBEYNDLU3WGZ 】- 2K moras 💰💰💰
👉【 4S5RTSV3P5CC 】- 60 Primogems 💎💎💎
...
🔗#Genshin Active Codes (October 2025).
Add @APKFreeDownloader_Bot to get any apk you want.