Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
👀 Well, would you look at that! 👆
#GUNUSDT reached 9th TP in under 6 hours!
Signal from our VIP PRO channel!
With a 5% entry and a $1000 deposit, you could've earned $414!
Every day we're on fire! 🔥🔥🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 How to earn every month with zero risk?
Become Propheta partner with zero investment required!
Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#bitcoin#btc#trading
👆 OMG! Would you look at that 👀
#GUNUSDT reached 9th TP in under 12 hours!
Signal from our VIP PRO channel!
Using a 5% entry you could've earned $430 with a $1000 deposit
ACCESS TO MANUAL TRADING for 70usdt/month
👉 We ain't only bragging about those profits, we're publishing the most transparent performance reports you can personally audit!
Come and see for yourself: @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptomarket#crypto#tradingview
👆 Propheta living up to its name yet again 🔮
#GUNUSDT has just reached 9th TP in the VIP CLUB channel!!!
Trade took just 8 hours! 👍
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Love the profits you're seeing, but can't afford the VIP cost?
Earn over $40 per one recommendation with zero risk using our referral program!
Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptonews#tradingindicator#trading
👆 OMG! Would you look at that 👀
Reached 9th TP on our #GUNUSDT trade! 🔥🔥🔥
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
👉 We will keep posting about how we earn money. Will you keep watching how someone else does it, or start earning yourself? Subscribe using our telegram bot: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrade#autotrading#tradingview
👍 This is why we're here!
Reached 9th TP on our #GUNUSDT trade! 🔥🔥🔥
$409 in profits with a 5% entry and a $1000 deposit!
ACCESS TO MANUAL TRADING for 70usdt/month
👉 Looking for a way to earn not only using signals?
Join our generous referral program and earn over $40 per recommendation!
Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptobot#crypto#tradingindicator
Now that's trading 👆🔥🔥🔥
#GUNUSDT reached 9th TP in under 23 hours!
Signal from our VIP CLUB channel!
You could've earned $307 with a 5% entry and a $1000 deposit!
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
💰Turn data into gains with Propheta AI Analyzer: deep AI analysis spots trends with surgical precision, tweaks in seconds to your goals, and pair hunting pumps your trading to the next level — this is the evolution of the game! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#ethereum#eth#buycrypto
👆 OMG! Would you look at that 👀
#GUNUSDT has just reached 9th TP in the VIP PRO channel!!!👍
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
👉 We know how to earn 3-4-5 digit amounts without any deposit, with zero risk! Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#bitcoinnews#tradingviewindicator#buyeth
👍 This is why we're here!
#GUNUSDT has reached 9th TP in the VIP CLUB signals channel!
Time elapsed: 10 hours! 👍
$312 in profits with a 5% entry and a $1000 deposit!
That's why we call it the "Money Printer" 💴💷💵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!
#bitcoinnews#tradingview#AItrade
#GUNUSDT reached 9th TP in under 2 days!
Signal from our VIP PRO channel!
Using a 5% entry you could've earned $401 with a $1000 deposit
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Only in our community will you get several useful channels for the price of one sub!
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptochannel#indicator#signalchannel
Oops, we did it again 🤣
#GUNUSDT has just reached 9th TP in the VIP PRO channel!!!
Trade took just 2 days! 👍
Easy $411 with a 5% entry and a $1000 deposit!
ACCESS TO MANUAL TRADING for 70usdt/month
👉 We ain't only bragging about those profits, we're publishing the most transparent performance reports you can personally audit!
Come and see for yourself: @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptobot#tradingbot#signals
👆 Propheta living up to its name yet again 🔮
#GUNUSDT has reached 9th TP in the VIP CLUB signals channel!
Time elapsed: 5 hours! 👍
Using a 5% entry you could've earned $326 with 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!
#tradingviewindicator#cryptocurrency#ethereum