Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Indian Delegation To Visit Russia For Next Round Of India-EAEU FTA Talks In June 2026 #Trade
🚨India, Russia-Led EAEU Bloc Had Launched Talks For An FTA On 26th November 2025
🚨The EAEU Comprises Of Russia, Kazakhstan, Armenia, Belarus, And Kyrgyzstan; With An Observer Status To Cuba, Moldova, And Uzbekistan
𝐀 𝐦𝐚𝐬𝐬𝐢𝐯𝐞 𝐰𝐢𝐧 𝐟𝐨𝐫 𝐈𝐧𝐝𝐢𝐚’𝐬 𝐞𝐱𝐩𝐨𝐫𝐭𝐞𝐫𝐬 🇮🇳🤝🇳🇿.
The India–New Zealand FTA signed today ensures 100% duty-free access across all tariff lines, eliminating earlier tariffs of up to 10% on textiles, leather, carpets, ceramics, and auto components, boosting competitiveness, cutting costs, and unlocking new markets. #Trade
Bangladesh to import 200 broad-gauge coaches from India by 2027
The project, financed by the European Investment Bank, is expected to see the coaches added to the Bangladesh Railway fleet between June 2026 and December 2027.
#trade
I’ve been on @Vault777Casino for a while now and it’s honestly one of the most engaging virtual trading platforms I’ve used to #trade
Fast predictions, leaderboards, rewards, and real strategy
⚡️ Storm Trade: Update Completed and New Features Announced
#TON#trade
The Storm Trade update has been completed successfully. The platform now uses the Pyth price feed protocol, offering faster and more accurate price updates. This upgrade enhances UI interaction and sets the stage for the upcoming V3 launch on TON.
Source: link
@tonlines
🇮🇳🤝🇰🇷 Looking forward to PM Modi visiting South Korea says SK President Lee Jae Myung
Indian Officials say an upgraded India-SK CEPA Agreement could be signed during the Visit.
2009 CEPA Agreement reduced Tariffs on 85% Indian Products to SK and 90% SK products to India
#Geopolitics#Trade
Trump sees resumption of trade with Russia as a guarantee of ending the conflict - Foreign Policy
In his policy of resolving the conflict in Ukraine, Donald Trump is betting to restore trade relations with Russia as the most important factor of peace. He argues that economic cooperation will benefit American investors and ensure stability in the region.
The US administration also believes that trade agreements with Russia, such as energy sector deals, can serve as a guarantor of peace.
#Trump#Russia#Trade
👂More on Trump's Ear
⚠️
Portals Community: Season 2 Launches with Points Farming
#Portals#trade
Portals Community announces the return of Points Farming with the launch of Season 2, allowing users to earn points and cashback on every trade. Users can enhance their progress by completing tasks, with more earning opportunities to come. Stay tuned for another major update arriving tomorrow.
Source: link
@tonlines