Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
📍 Mount Teide, Tenerife Island, Spain 🇪🇸
🌋 Mount Teide is located in the center of the largest of the Canary Islands - Tenerife. The mountain, which can be seen today from any point on the island of Tenerife, grew more than a hundred thousand years ago from the depths of the ancient stratovolcano Las Cañadas, the top of which once collapsed inward under the weight of the erupting lava.
This majestic peak, standing at 3,718 meters (12,198 feet), is the highest point in Spain and the third highest volcano in the world, rising from its base on the ocean floor. The surrounding Teide National Park boasts an otherworldly landscape of volcanic craters, lava fields, and unique flora and fauna. A cable car ride to the top offers breathtaking views of the island and the Atlantic Ocean beyond. 🌋🚠
#travel#adventure#canaryislands
🇪🇸🇮🇨Spain says over 1,000 migrants reached its Canary Islands in 3 days as more attempt deadly crossing
More than 1,000 migrants from sub-Saharan countries arrived in Spain's Canary Islands in 18 boats over the past three days, Spain's marine rescue service said on Monday.
The archipelago off northwest Africa has seen a surge in migrant arrivals in recent weeks as more people from West Africa attempt to get their, which is a dangerous trip.
Officials say 7,270 migrants arrived in January, about as many as in the first six months of 2023.
Most of the boats depart from Mauritania. Spanish Prime Minister Pedro Sánchez and European Commission President Ursula von der Leyen will visit the West African country on Thursday to encourage authorities to try to curtail the departures.
#Spain#CanaryIslands
@africaintel
Drone drops food for dogs trapped in La Palma by volcano lava
Several emaciated dogs lie curled up in and around a walled, ash-covered yard cut off by volcanic lava in the mountainous area of Todoque, on the Spanish island of La Palma, until a drone appears in the sky to drop packages with food and water.
#CanaryIslands#LaPalma#volcano#Spain#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Sunspots seen in Spain as geomagnetic storm expected
Sunspots were seen from Spain's Canary Islands as a geomagnetic storm was expected to reach the Earth.
#Sunspots#Spain#CanaryIslands#GeomagneticStorm#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Red-hot lava forces evacuations in Spain's La Palma
Over 700 residents on the Spanish island of La Palma were ordered to abandon their homes as lava advanced toward their neighborhoods.
#LaPalma#Spain#volcano#CanaryIslands#CumbreVieja#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
🐟 Rare Encounter with the “Sea Devil” near the Canary Islands!
For the first time in history, biologists managed to capture this mysterious deep-sea predator on video. Usually, only larvae or dead specimens are observed, as anglerfish live at extreme depths where almost no light reaches. But this time, the fish rose to the surface and appeared in front of the researchers’ camera — a truly unique observation for science!
#MarineLife#Anglerfish#DeepSeaMysteries#CanaryIslands☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
Lava spews from La Palma volcano
The Cumbre Vieja volcano on Spain's La Palma island continues to spew lava and smoke.
#Volcano#LaPalma#Spain#Lava#CanaryIslands#CumbreVieja#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Volunteers take in La Palma's homeless pets
This makeshift shelter in La Palma, Spain, is housing hundreds of homeless pets after their owners were forced to flee from the Cumbre Vieja volcano.
#Volcano#LaPalma#Spain#Lava#CanaryIslands#CumbreVieja#HomelessPets#Pets#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖