Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Planning to make full use of the Vaccinated Travel Lanes this holiday season, or heading for a staycation?
Don’t forget to go through the ‘Check and Protect’ checklist for a thorough #MozzieWipeout of your home before you head off! https://go.gov.sg/dengue-checklist
Sudden rain showers are common in Singapore, so if you leave your pails or plant pots where they can collect water, do pay extra attention and drain these containers if they have collected any water.
Here’s a checklist for a thorough #MozzieWipeout: https://go.gov.sg/dengue-checklist
Have you emptied out your flower pot plates after watering your plants today? These plates tend to collect water, and can become mosquito breeding habitats if left unattended. Be sure to add emptying out the flower pot plates to your “To-do List” after watering your plants! Here’s a checklist for a thorough #MozzieWipeout: https://go.gov.sg/dengue-checklist
The annual National Dengue Prevention Campaign was launched today, to rally everyone to take urgent action to prevent mosquito breeding and a possible surge in dengue cases, amidst the continued high Aedes aegypti mosquito population, and higher circulation of less common Dengue virus serotypes.
The fight against dengue involves all of us. Let’s step up dengue prevention by doing the #MozzieWipeout regularly. go.gov.sg/mozzieproof
Planning a staycation with your SingapoRediscover vouchers? Keep yourself and your loved ones safe by going through the ‘Check and Protect’ checklist for a thorough #MozzieWipeout before your stay! https://go.gov.sg/dengue-checklist
Staying home during this COVID-19 period has brought out the green thumb in many of us. And yet, with interest comes responsibility, too! Set a daily reminder to keep your plants nourished and your home protected from dengue too: https://go.gov.sg/dengue-checklist#MozzieWipeout
The gully traps in our homes are perfect for mosquito multiplication! Cover rarely used gully traps or install anti-mosquito valves, to prevent mosquito breeding. Here’s a ‘Check and Protect’ checklist for your thorough #MozzieWipeout today: https://go.gov.sg/dengue-checklist
Do you know where are the favourite places for mosquitoes to lay their eggs?
Pails, flower pot plates/trays and ornamental vases are some of the persistent mosquito breeding habitats in homes. It’s time to search for and destroy these breeding habitats! If you’re not sure how, get started here: https://go.gov.sg/dengue-checklist#MozzieWipeout
The number of weekly dengue cases has declined by more than 50% from its peak this year. However, a 12% increase in the Aedes aegypti mosquito population was detected in the last 3 weeks.
So let’s not let our guard down; continue doing the #MozzieWipeout at least once a week and taking protective actions (go.gov.sg/stopdenguenow). You can also get regular alerts on areas with higher Aedes mosquito population and dengue clusters on myENV app (www.nea.gov.sg/myENV) with this step-by-step guide!
Think it’s impossible for mosquito eggs to hatch in your dish tray, mere inches away from your cups and plates? It certainly isn’t. All mosquitoes need is a 20 cent-sized drop of water to breed. Time to do a thorough check in your house! #MozzieWipeouthttps://go.gov.sg/dengue-checklist
Besides doing the #MozzieWipeout, take these 3 simple actions to protect yourself and your loved ones, especially if you live in a dengue cluster area: Spray, Apply, Wear. More tips here: www.nea.gov.sg/stop-dengue