Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🌎 Deep inside Mount Rainier, rare mineral caves called "Paradise Ice Caves" form as flowing air carves tunnels through compacted mountain ice, creating shimmering blue chambers that slowly change shape with the seasons. ✨
#geology⚡#glaciers⚡#minerals
👉subscribe Interesting Planet
🌎 Powerful enough to move mountains, glaciers shaped entire continents. As they advanced, their slow, grinding ice carved out valleys, lakes, and fjords still visible today. ✨
#geology⚡#glaciers⚡#landscapes
👉subscribe Interesting Planet
Climate change: World's glaciers melting at a faster pace - #Climatechange#Glaciers#World - https://www.bbc.com/news/science-environment-56921164@lovelynature
🌎 Glacial ice cores are frozen natural records of Earth’s past atmosphere. As snow compacts into ice, it traps tiny air bubbles that preserve ancient air. Scientists analyze these bubbles to measure past greenhouse gas levels, revealing climate changes that go back over 800,000 years. ✨
#geology⚡#climatehistory⚡#glaciers
👉subscribe Interesting Planet
🌎 In the heart of the Torres del Paine National Park in Chile, the Valle del Francés or "French Valley" mystifies visitors with its eerie groaning noises. The sounds come from glaciers cracking and shifting above, sometimes echoing like distant thunder across the silent rocky landscape—a wild reminder of Earth's restless, mysterious forces at work. ✨
#mysteries⚡#glaciers⚡#Chile
👉subscribe Interesting Planet
🌍 Water trapped as snow and ice in the Himalayas slowly melts each spring, feeding rivers that bring life to billions across Asia. This seasonal meltwater is key to the region’s water cycle. ✨
#hydrology⚡#rivers⚡#glaciers⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Rapid melting of glaciers is raising global sea levels faster than expected, contributing to increased flooding risks in coastal cities and threatening freshwater supplies for millions worldwide. ✨
#climate⚡#glaciers⚡#flooding⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some mountain glaciers now lose over a meter of thickness each year due to warming temperatures. This rapid melt threatens fresh water supplies for millions living downstream. ✨
#glaciers⚡#climate⚡#water⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Antarctica is home to “blue ice” areas where strong winds strip away snow and expose centuries-old glacier ice, creating shimmering fields that reflect nearly as much sunlight as fresh snow. ✨
#glaciers⚡#Antarctica⚡#polar⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In Antarctica’s Dry Valleys, glaciers flow slowly over bare rock and create icy waterfalls called “ice falls,” frozen in mid-cascade for years in the planet’s coldest, driest desert region. ✨
#glaciers⚡#Antarctica⚡#polar⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In Antarctica’s McMurdo Dry Valleys, some glaciers create striking red waterfalls called “Blood Falls.” The color comes from iron-rich water oxidizing as it flows out of the ice. ✨
#glaciers⚡#polar⚡#Antarctica⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Some Antarctic glaciers can move several meters in a single day, driven by gravity and melting underneath. These "ice rivers" shape the landscape faster than most people imagine. ✨
#glaciers⚡#polar⚡#Antarctica⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍