Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🌍 One of the youngest islands on Earth, Hunga Tonga-Hunga Haʻapai, formed in 2015 after an undersea volcanic eruption. New land like this is rare and offers scientists a natural laboratory. ✨
#islands⚡#volcanoes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 The maleo bird of Sulawesi uses volcanic heat to hatch its eggs! It buries them in warm sand or soil, letting Earth's warmth do the work, and the chicks dig themselves out and run off ready to face the world—a rare strategy among birds. ✨
#volcanoes⚡#birds⚡#adaptation
👉subscribe Interesting Planet
🌎 Towering above Tanzania, Mount Kilimanjaro is the world’s tallest free-standing mountain. Unlike mountain ranges, it rises alone from the plains, formed by ancient volcanic eruptions. Its snowy peak is a surprising sight just south of the equator. ✨
#geology⚡#volcanoes⚡#Africa
👉subscribe Interesting Planet
🌎 Rising from an ancient volcanic crater, Aogashima is a remote Japanese island village with about 170 residents. The island’s school has fewer than 10 students, and access is by boat or helicopter due to rough seas and no airport. ✨
#geography⚡#settlements⚡#volcanoes
👉subscribe Interesting Planet
👉more Channels
🌍 Mount Etna in Italy is one of the world’s most active volcanoes, but it’s also growing taller each year as repeated eruptions pile new layers of lava onto its summit. ✨
#mountains⚡#volcanoes⚡#geology⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 Layers of volcanic ash preserved in sediments create natural records of Earth's explosive history. By analyzing ash layers, scientists can pinpoint ancient eruptions and trace how ash traveled across continents. Some distant ash deposits reveal supervolcano eruptions that spread material for thousands of kilometers. ✨
#volcanoes⚡#geology⚡#sediments
👉subscribe Interesting Planet
👉more Channels
🌎 At the heart of Africa, Lake Nyos hides a deadly secret—an underwater layer of carbon dioxide gas that once erupted, suffocating everything nearby in 1986. This rare “limnic eruption” happens when gas builds up at depth and suddenly bursts to the surface, releasing an invisible, odorless cloud with devastating effects. ✨
#volcanoes⚡#disasters⚡#geology
👉subscribe Interesting Planet
🌍 Earth’s mountain-building processes are still active—over 80% of volcanoes erupt near tectonic plate boundaries, constantly creating new land and even islands in the world’s oceans. ✨
#geology⚡#volcanoes⚡#oceans⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 Around 252 million years ago, the Permian-Triassic extinction wiped out about 90% of marine species and 70% of land vertebrates. Massive volcanic eruptions in Siberia released greenhouse gases that drove rapid global warming, ocean acidification, and low oxygen levels—making it the largest extinction event in Earth's history. ✨
#extinction⚡#volcanoes⚡#paleoclimate
👉subscribe Interesting Planet
👉more Channels
🌎 In northeast Azerbaijan, the Gobustan Mud Volcanoes regularly erupt with cool, viscous mud instead of lava. These eruptions can blast columns up to 200 meters high. About half of the world’s estimated 1,000 mud volcanoes are concentrated in this region, producing unique surface features and even spontaneous flames when natural gas ignites. ✨
#Azerbaijan⚡#volcanoes⚡#geology
👉subscribe Interesting Planet
👉more Channels
🌍 The ring-shaped chain of volcanoes called the "Ring of Fire" circles the Pacific Ocean, hosting about 75% of all active volcanoes on Earth and causing frequent earthquakes and eruptions. ✨
#volcanoes⚡#mountains⚡#tectonics⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Mount Erebus in Antarctica is one of the world’s southernmost active volcanoes. Its lava lake stays liquid year-round, despite harsh temperatures that often plunge far below freezing. ✨
#volcanoes⚡#Antarctica⚡#mountains⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍