Функция 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
🏝️ Tourism tax levy on Bali
The new tourism tax levy, introduced on the 14th of February, 2024, makes it mandatory for all international tourists to pay IDR 150,000 ($9.25) in tourism taxes.
The Bali Tourism Police have been instructed to conduct more spot checks on tourists to catch those who have not paid the tourism tax levy.
Despite the fact that the new tourism tax has already raised $3.9 million, this is only a fraction of what tourism officials should have in the bank by now.
It has been calculated that as much as 60% of tourists haven’t been paying their tourism tax levies.
@BaliNews
#economics#tourism
📈Indonesian economy grows faster than forecasts
📰 Indonesia's GDP growth for 2Q 2024 was 5.05%, exceeding analysts' forecasts, according to the country's statistics agency.
📈 Household consumption remains the main sector of the Indonesian economy with a contribution to overall growth of 55%. Manufacturing and construction sectors are next in terms of volume.
👍 The country's finance minister forecasts GDP growth of more than 5% for the whole of 2024.
@BaliNews
#goodnews#economics
🤑Bali to make a center for family offices in the region
🏝 Investment Minister Luhut has proposed to make Bali an alternative center for wealthy investors, on par with Singapore and Hong Kong, which are setting up family offices to do business.
📈 The minister shared statistics from Singapore, where there is a boom in such offices and added that he is now receiving many requests to set up an investment hub in Bali between Singapore, Hong Kong and Dubai.
🪙 A number of issues remain to be sorted out by the authorities to make this possible. First and foremost is to amend the tax laws or create a special economic zone in Bali. So far all income, including foreign income, such offices will have to declare inside Indonesia and pay taxes on it. This goes against the classical offshore jurisdictions, where such income is not taxed.
#statistics#economics
📈Indonesia's budget for 2025 – which sectors are expected to grow the most
The Indonesian government approved a $230 billion budget for next year. Bloomberg looked at which sectors of the Indonesian economy will benefit from it, and which public companies will show the most growth.
📈The obvious winners of the new budget:
・Food industry
・Healthcare
・Commercial and hotel real estate
・Automotive industry
・Mining
・Green energy
That said, there are also potential losers in the form of large construction companies following a 6% cut in infrastructure spending.
Overall, Indonesia's stock market has performed enviably well when compared to Europe or Asia. For example, the growth over 10 years amounted to 47%.
@BaliNews
#economics#business
💰 BlackRock установили рекорд — под их управлением $11 триллионов. Компания управляет активами, которые превосходят по своей капитализации ВВП Китая, Индии и РФ вместе взятых.
Black Rock - это не просто инвесторы. Это и есть реальная власть, управляющая миром с помощью финансовых инструментов.
BlackRock владеет блокирующим пакетом акций в половине публичных компаний США. У фонда около 10 % акций Coca-Cola и PepsiCo, он является крупнейшим инвестором в Boeing и Airbus, Apple и Microsoft. Также Black Rock владеет акциями конкурирующих горнодобывающих и нефтяных компаний, сталелитейных заводов, автомобильных гигантов и, банков, в том числе всех из так называемой "большой четверки".
Им же принадлежат блокирующие пакеты акций в трех крупнейших фармацевтических компаниях Америки - Pfizer, Johnson & Johnson и Merck.
Есть данные, что под непрямым управлением Black Rock находится порядка 10 % всех финансовых активов мира. Но данные остаются остаются слухами, потому BlackRock владеет от 8 до 18 % акций таких крупнейших медиакомпаний, как CNN, CBS, Fox, Disney, ABC.
#Economics#Окно_Овертона
Emir in India: Whenever Modi has a bilateral visit, Adani’s not far behind
https://www.newslaundry.com/2025/02/19/emir-in-india-whenever-modi-has-a-bilateral-visit-adanis-not-far-behind
https://archive.vn/fyWKK
#geopolitics#economics#india
🌍 The world’s largest diamond trading hub is not near a mine but in Antwerp, Belgium. Over 80% of all rough diamonds pass through this city, shaping global trade far from their origin. ✨
#economics⚡#trade⚡#cities⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels