Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🙈 After the ban on accepting organic waste, Bali authorities faced an unexpected consequence: residents began massively burning trash right in their own yards
ℹ️ The decision to restrict organic waste intake was made to accelerate the transition to village-level waste processing systems. Now the island’s largest landfill only accepts non-organic and residual waste. The reason is critical overload: up to 65% of Bali’s waste is organic with high moisture content, leading to methane emissions, unpleasant odors, and rapid overfilling of the site.
🔥 However, in practice, the ban has triggered a wave of uncontrolled waste burning. Lacking sufficient recycling infrastructure, local residents have resorted to the simplest method of disposal – fire.
#rules@BaliNews
🌱 Bali’s main landfill stopped taking organic waste (April 2026) and will fully close by August
👮♀️ Police are monitoring the site, but short-term issues like illegal dumping and river pollution may increase during the transition.
🚮 Tourists: you might notice more trash in some areas – travel responsibly.
#rules@BaliNews
🪧Bali installs signs with rules of behavior on the island
📰 The Department of Tourism of Bali province is concerned about the number of violations of the rules of behavior on the island by tourists. Now it is intensifying the installation of information signs with infographics explaining the rules of behavior on the island – Do's and Don'ts.
📍 The plan is to install these signs at 10 key locations in Kuta, Changgu, Seminyak, Uluwatu, Tanah Lote and Bedugul where the chance of reading the rules will be high.
🤞 This is expected to reduce the number of violations so often committed by foreign tourists.
What Do's should be followed first of all?
@BaliNews
#tourism#rules
👮♂️Governor to take firm and tough action against foreign tourists who behave badly while in Bali
📰 The statements come after an American national was arrested and deported after going on a rampage in a hospital on the island under the influence of drugs.
🇺🇸 The 27-year-old US citizen, known by his initials MM, tested positive for drugs, though was deported from Indonesia without criminal prosecution as ‘no evidence’ was found to charge him with drug possession.
❌ He has been added to the blacklist and will be denied entry to Indonesia in the future.
@BaliNews
#rules#goodnews