Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
names = [
'image.bmp',
'second.txt.bkp',
'data.db',
'.config.cfg',
'file.ext.bkp'
]
И мы хотим убрать у них окончание ".bkp".
Не знаю зачем, пример довольно надуманный) Но суть он показывает, а это главное.
Те, кто еще не очень знаком с библиотекой os.path или pathlib, вероятно решат обработать имена как строки. И тут вполне подойдет метод строки strip().
Что делает этот метод? Он отрезает указанные символы по обеим сторонам строки. Если ничего не указать, то убирает невидимые символы (пробелы, табуляции и переносы строк).
В нашем случае будет выглядеть вот так:
>>> name.strip('.bkp')
То есть просим удалить строку '.bkp' по краям имени файла, если таковая есть.
Можно применить аналогичный метод rstrip(), чтобы отрезать только справа, но для этого примера используем обычный.
>>> for name in names:
>>> print(name.strip('.bkp'))
image.bm
second.txt
data.d
config.cfg
file.ext
Хм, что-то не то с нашими именами! Что случилось??? Видим нежелательное переименование в именах, где и близко не было указанной строки '.bkp'
А дело всё в том, что данный метод ищет не указанную строку, а указанные символы, и не важно в каком порядке.
Для метода strip() строка '.bkp' это не паттерн для поискаа список символов. Потому он отрезал симовол 'p' от '.bmp' и удалил точку из файла '.config.cfg'.
Как тогда правильно заменить именно паттерн? Для начинающего можно посоветовать метод строки replace(), который как раз использует для замены указанную строку целиком. В нашем примере заменим её на пустую строку.
>>> for name in names:
>>> print(name.replace('.bkp', ''))
image.bmp
second.txt
data.db
.config.cfg
file.ext
Уже лучше, но помните, это лишь пример про strip(). Для работы с именами файлов есть способы и более "правильные", дающие однозначно верный результат. Я взял файлы только в качестве примера. Даже replase() тут может сделать не то что ожидаем.
Просто впредь будьте внимательны с этим strip().
#basic
🏝️ 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