Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
👍 This is why we're here!
Reached 9th TP in the VIP HTL channel!
$308 in profits with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 45usdt/month
👉 Looking at those reports and can't believe what you're seing?
Go to our reports channel and audit us! @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#buycrypto#cryptochannel#trading
👍 This is why we're here!
Reached 9th TP in just 7 hours in the VIP HTL channel!
With a 5% entry and a $1000 deposit, you could've earned $206!
ACCESS TO MANUAL TRADING for 70usdt/month
📊Dominate the market with Propheta AI Analyzer: AI uncovers hidden patterns with razor-sharp analysis, adapts on the fly with slick customization, and delivers next-level pair hunting — your edge for strategic supremacy! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#passiveincome#cryptobot#cryptochannel
Reached 9th TP in the VIP PRO channel!
ACCESS TO MANUAL TRADING for 70usdt/month
👉 In our VIP community, not only will your deposit grow, but your skill as a trader as well!
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#buybtc#crypto
Oops, we did it again 🤣
Reached 9th TP in the VIP PRO channel!
You could've earned $603 with a 5% entry and a $1000 deposit!
Feels good to be a Propheta VIP, man... 🏖ACCESS TO MANUAL TRADING for 70usdt/month
👉 Multiplying deposits every day!
Not convinced? Contact us for a free trial - @propheta_help
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrader#passiveincome#cryptochannel
Reached 9th TP in just 3 hours in the VIP PRO channel!
Easy $513 with a 5% entry and a $1000 deposit!
Every day we're on fire! 🔥🔥🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Time to start earning for real!
Join us >>> t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#signalchannel#AItrader
Reached 9th TP in the VIP HTL channel!
You could've earned $214 with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
👉 Time to start earning for real!
Join us >>> t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#buyeth#bitcoin
👆 Propheta living up to its name yet again 🔮
Reached 9th TP in just 1 hour in the VIP HTL channel!
You could've earned $306 with a 5% entry and a $1000 deposit!
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Did you know that many traders use our performance reports to build their own trading strategy? That's how useful they are! Check them out: @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptonews#indicator#cryptochannel
👀 Well, would you look at that! 👆
#ENAUSDT has just reached 9th TP in the VIP CLUB channel!!!👍
With a 5% entry and a $1000 deposit, you could've earned $461!
Every day we're on fire! 🔥🔥🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Not sure? Considering? Contemplating? Come have a look at our performance reports, spend about5 minutes and see for yourself that everything is 100% legit! @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrader#cryptobot#cryptochannel
#ENAUSDT reached 9th TP!
Signal from our VIP HTL channel!
You could've earned $302 with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
👉 Did you know that our referral partners receive extra discounts, even cumulative with the special offer prices?
START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#signalchannel#cryptobot
Oops, we did it again 🤣
#ENAUSDT reached 9th TP in under 2 days!
Signal from our VIP PRO channel!
With a 5% entry and a $1000 deposit, you could've earned $603!
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
👉 Looking at those reports and can't believe what you're seing?
Go to our reports channel and audit us! @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#buybtc#tradingindicator
Oops, we did it again 🤣
Reached 9th TP in 1 day on our #ENAUSDT trade! 🔥🔥🔥
Using a 5% entry you could've earned $462 with a $1000 deposit
ACCESS TO MANUAL TRADING for 70usdt/month
👉 It's time to get a moneyprinter of your own!
Get access: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#btc#CryptoSignal
Reached 9th TP in 14 hours on our #BBUSDT trade! 🔥🔥🔥
Using a 5% entry you could've earned $199 with a $1000 deposit
ACCESS TO MANUAL TRADING for 70usdt/month
👉 It's time to get a moneyprinter of your own!
Get access: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#bitcoin#AItrading