Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
#Web3Festival in Hong Kong wrapped up during a tough week for the crypto market, but builder momentum was high and the community remains active 🔥
Announcements such as TON Blockchain's TON wallet expanding into the U.S. and events hosted by Monad and BNB Chain indicate that the space is still moving forward.
For a recap on highlights from this past week, read the DWF Ventures team's summary here.
DWF Ventures continues to support teams building through every cycle. If you're working on something, get in touch: https://www.dwf-labs.com/ventures
During our week at #Web3Festival in Hong Kong, Eugene Ng, Founding Partner of DWF Labs, gave a talk on the mainstage about the newest trends and narratives in Web3 innovations.
He discussed the rise of Bitcoin ecosystems, the institutionalisation of crypto as an asset class; memecoins, AI and more. 💥
Missed his speech? Check out the livestream recap.
#Web3Festival was a successful week, and we especially enjoyed our side event, DWF Labs Haus, on Sunday night. 🌙
It was an evening of delicious cocktails and canapés, fantastic company, and insightful conversations. Thank you to everyone who came!
During #Web3Festival Hong Kong, our team was able to share insights about innovations that are heating up in the crypto space. 🔥
Yesterday, Fiona Ma, Senior Associate at DWF Ventures, gave a speech about decoding the Ethereum restaking landscape, delving into the evolution from staking to restaking.
Restaking is one of the verticals DWF Ventures is highly interested in - if you're a project innovating in multiple sectors, feel free to reach out to their team on X!
Our team had an amazing time at #Web3Festival in Hong Kong!
It was our second year sponsoring Web3 Festival, and this year was even bigger and better than the last. 🔥
It was a pleasure to meet our friends and partners in person at our booth. Thank you to everyone who came by!
About last night... 👀
That's a wrap on our event, DWF Labs Haus, during #Web3Festival Hong Kong. 🔥
Meeting industry leaders, founders, and innovators in person is always a pleasure as we continue to work from a diverse network of cities and countries worldwide.
Thank you to everyone who attended, it was great to meet you all!
Setting up for our DWF Labs Haus event during #Web3Festival, which kicks off at 6 PM. 👀
We're in full swing gearing up to host an unforgettable evening filled with incredible networking opportunities and delicious cocktails and canapés.
Looking forward to meeting everyone soon!
The teaser for Hong Kong #Web3Festival 2024 just dropped!
We're excited to be Title Sponsors of this event ✨
Get ready for this spectacular gathering of #Web3 set for April 6-9 🔥
Get February offer: https://lu.ma/hkweb3festival2024
🌎TONCA$H Travel Cashback is ON!
Planning to hit Hong Kong #Web3Festival or Dubai #Token2049? Why not earn cashback in $BTC, $TON, or $USDT when booking your trip?
Hot Deals:
⚡️ 10% cashback on flights🛬
⚡️ 20% cashback on hotels📍
How to Claim?
✅ Book your trip via TONCash App
✅ Receive your cashback in $BTC, $TON, or $USDT directly in your wallet! T&Cs apply
💵Get Your Place Now!🏝
#TONCash#Travel#Web3#HongKongWeb3Festival#DubaiToken2049#Cashback