Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🚨CyberCharge discount sale ends, price back to $198! 🚨
Thanks to all our supporters — nearly 10,000 devices shipped globally 🌎
More users are joining the Web3 journey of earning while charging ⚡️
CyberCharge is becoming the 1 choice for #DePIN earners.
🔥Follow us for occasional limited-time $148 promotions!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
TWITTER SPACE!!
🕊
🚀 Join us on Aug 20th at 12 PM UTC for a Twitter Space on the #DePIN wave!
📚Topic: Can the Bitcoin ecosystem become the new battleground in the DePIN wave?
📍https://twitter.com/i/spaces/1DXxydzBZVNJM
👥 Panel:
- @CyberChargeJoe
- @MasterOfCoins from MyCoralApp
- @MelosBoom
- @Dr_lovelyman from Tap protocol
- @YProselkov from WebKey01
Don't miss it! CyberCharge
Like👍, Retweet🔁, Comment
Link to the tweet!
⚡️CyberCharge – The one charger to power them all!
🔋Revolutionize your energy needs with cutting-edge technology designed for the future.
👉cybercharge.org looking forward to more updates on the #DePIN revolution in energy.
Like👍, Retweet🔁, Comment
Link to the tweet!
We are thrilled to partner with SrcAi_Official!
🚗 SRC ai is an AI-powered Web3 app that monetizes routine driving data, transforming driving habits into recorded and rewarded activities. Monetize your driving data and contribute to the advancement of autonomous tech with SRC ai.
🔋 CyberCharge is the next-generation global power matching protocol and the world's first #DePIN C2E network focused on charging and mining.
We will drive AI and blockchain growth together while exploring new opportunities.
Like👍, Retweet🔁, Comment
Link to the tweet!
💡CyberCharge is the world's first smart charger that combines #Web3 and #DePIN to turn every charge into a digital currency reward while supporting the decentralized Web3 network.
We've got even more rewards for you in Miniapp, where you can draw free treasure chests for tokens like $SOL, $TON, and more!
Let's unleash the full potential of the Cybercharge ecosystem!
After completing all the @taskonxyz 50 winners will receive an equal amount of gems with a total value of $200!
Join: https://taskon.xyz/quest/404918461
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
⚡️CyberCharge is proud to sponsor the R3alWorld Summit 2024 at #TOKEN2049 .
🤝Join us in Singapore as we showcase the future of decentralized energy solutions and participate in key discussions on the #DePIN industry
Like👍, Retweet🔵, Comment
Link to Tweet
🎁Join our Airdrop Event
Link to MiniApp
Link to IoTeX tweet:
The Future of DePIN: Energy at its Core
⚙️DePIN is transforming Web3, enhancing energy security and adaptability with real-time distribution and monitoring.
⚡️In Low-Voltage transmission, it boosts safety, responsiveness, and efficiency.
#CyberCharge#DePIN
Like👍, Retweet🔵, Comment
Link to Tweet
🤖Join Bot🐣X (Twitter)✉️Chat
Don't miss out #CyberCharge Charger 🥳
Check out the tweet below to learn how to enter the biggest #DePIN giveaway IN HISTORY. 👇
Click Here
Like👍, Retweet🔵, Comment
Link to Tweet
🎁Join our Airdrop Event
Link to MiniApp
🤝#CyberCharge is teaming up with @Weaver_Labs, leaders in Telecom and #DePIN innovation!
📡Weaver Labs is transforming the telecom industry with blockchain-powered decentralization via Cell-Stack, making connectivity accessible for everyone!
🔋CyberCharge, the world's first DePIN C2E network, combines charging and mining, powered by a global weak-voltage power matching protocol.
Like👍, Retweet🔵, Comment
Link to Tweet
🎁Join our Airdrop Event
Link to MiniApp
🚀#CyberCharge is kicking off its Global Tour at @token2049 Singapore!
📍First stop: Marina Bay Sands, 18-19 September 2024.
🤝Come visit our Main Event Booth M126 (Level 4) and experience the future of #DePIN innovations firsthand
Like👍, Retweet🔵, Comment
Link to Tweet
🎁Join our Airdrop Event
Link to MiniApp