Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
➡️New build available for Xiaomi Redmi 9 Prime / Poco M2 (lava)
👤 by Sakthivel Nadar
ℹ️ Version: 13
📆 Build date: November 14, 2022 05:22
📂 File size: 1.62 GB
⬇️ Download now
#lava#pixelexperience
🪐 The exoplanet 55 Cancri e, orbiting a star about 41 light-years away in the constellation Cancer, is known for its fiery dayside, reaching temperatures above 2,400°C—hot enough to melt metal. This rocky world is likely covered by a massive ocean of molten lava, and some scientists think its carbon-rich composition could even mean parts of the planet’s interior are made of diamond. ✨
#exoplanets⚡#extremes⚡#lava⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Far from Earth, the exoplanet COROT-7b endures some of the most extreme conditions known: it orbits its star so closely that its surface reaches about 2,000°C, hot enough to melt rock. Scientists believe this heat turns the planet’s rocky crust into a vast, bubbling “lava ocean,” creating a world where rock vaporizes into the atmosphere and rains down as pebbles. ✨
#exoplanet⚡#extremes⚡#lava⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
Lava in Spain's La Palma engulfs more houses
Lava engulfed more buildings on the Spanish island of La Palma, destroying everything in its path about three weeks after the volcano began to erupt
#News#Reuters#LaPalma#Spain#Lava
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➖
Spain's volcano is still erupting, no end in sight
There's no end in sight to the volcanic eruption that has caused chaos and destruction on the Canary island of La Palma since it began about a month ago
#News#Reuters#LaPalma#Spain#Lava#Volcano
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➖
LIVE: Building-sized lava blocks fall from volcano on Spain's island La Palma
Blocks of molten lava as large as three-story buildings rolled down a hillside on the Spanish island of La Palma on Sunday while a series of tremors shook the ground three weeks after the volcano erupted.
#News#Reuters#Live#volcano#lava#LaPalma#Spain
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➖
LIVE: Lava spreads on Spain's La Palma with no end in sight to volcanic eruption
Flows of molten rock pour from the Cumbre Vieja volcano — in its fourth week of eruption — threatening to engulf another area on the Spanish island of La Palma.
#News#Reuters#Live#volcano#lava#LaPalma#Spain#environment
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➖
LIVE: Drone captures view of La Palma's Cumbre Vieja volcano
Drone footage shows the impact of the Cumbre Vieja volcano on La Palma, Spain.
#News#Reuters#Live#volcano#lava#LaPalma#Spain#environment
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➖
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➖