Функция 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
Trump Does Not Shy Away From His Plan to Topple Down Khamenei
The US is weighing precision strikes on "high-value" Iranian officials and commanders who it deems responsible for the deaths of protesters, a Gulf official familiar with the discussions told Middle East Eye.
The strikes could come as early as this week, but that timeline could shift, MEE was told on Monday.
Discussions within the administration have been described as “chaotic”, with a debate over what the repercussions will be in terms of Iranian retaliation.
The Trump administration has toyed with attacking Iran for nearly a month on the pretext of the brutal crackdown on demonstrators that has seen thousands killed by government security forces.
After calling on demonstrators to "take over" state institutions, President Donald Trump backed down and said the “killing has stopped”.
Trump’s decision to de-escalate came as Gulf states, namely Saudi Arabia, Qatar and Oman, lobbied against strikes.
While some reports framed Trump's remarks as drawing a curtain on US intervention, former US officials and analysts told MEE they appeared to signal a pause.
Trump moved up and down the escalation ladder in a similar fashion with Venezuela, before finally ordering an attack on the Latin American country that resulted in Maduro's abduction and detention in the US.
A former US intelligence official told MEE that their understanding of conversations within the administration is that Trump has not given up on pushing for “regime change” in Tehran.
A former US official told MEE that the US has been working to replenish supplies of missile interceptors exhausted during the 12-day war with Iran in June and that “total supplies” had moved up. The US is still constrained, as it provides supplies to Ukraine.
US Central Command said on Monday that the Abraham Lincoln aircraft carrier was in the Middle East after sailing from the South China Sea.
“We have a big force going toward Iran. I’d rather not see anything happen, but we’re watching them very closely,” Trump said on Thursday evening on his return to Washington from Davos, Switzerland.
The Abraham Lincoln carries F-35 warplanes and F/A-18 jet fighters, in addition to EA-18G Growler electronic-warfare planes. It is also accompanied by guided-missile destroyers.
Open-source flight trackers have also reported that the US has built up a squadron of F-15 warplanes at Muwaffaq Salti Air Base in Jordan.
The build-up of warplanes in Jordan would give the US options, as Gulf states have imposed a ban on the US using their airspace or facilities to launch strikes on Iran, current and former US and Arab officials told MEE.
That ban has been in place since April 2025, MEE first reported.
#trump#kill#khamenei#iran#US
📱American Оbserver - Stay up to date on all important events
🇺🇸
While in #Lugansk People's Republic (formerly Ukraine), I got to watch as their forces disabled the #mines placed by the #Ukrainian army; mines meant to #kill the civilians that were sent to repair the electrical power plant.