Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Want to share a $200 pool?
The HTX May Referral Campaign is LIVE! 🚀
✔️ Follow @HTXCommunity + RT
📱 Invite friends to join HTX Telegram + 2nd Group
🔥 Generate your unique invite link via our TG admin & start inviting
More invites = More #rewards. Let’s grow together! 📈
➡️Join NOW
✈️Telegram | ✖️X
✈️Announcements
🎙️ AMA Alert | 🎁 Win $200
Everything you need to know about New Funds Bonus Rules —simple, clear, no fluff.
🗓 11 Feb | 10:00 AM (UTC)
✅ Follow @HTXCommunity + RT
📍 Venue: HTX English Telegram Group
Set your reminder & come learn how to maximize your #rewards
➡️Join Now!
✈️Telegram | ✖️X
✅Announcements
🚀Gamety Monthly Run I is LIVE on Zealy!
Another chance to win $500 in $GTY!
🔗 Join now: https://zealy.io/cw/gagentai
🏆 Top 20 Zealy users will be rewarded:
🥇 1st Place – $75
🥈 2nd-10th – $30 each
🥉 11th-20th – $16 each
Don’t wait! Complete Zealy tasks now and climb the leaderboard!
#Rewards will be distributed 1 month after the campaign ends.
🔈Don’t miss this $GTY Era/ 🕊Tweet
📎Important Links:
$GTY Dextools|Website | X | Chat (FULL) | Indonesian Chat | African Chat | Vietnamese Chat | CIS Chat | Discord | Announcement | YouTube | Medium | New Bot | $GTY Staking | $GTY Coinstore
🚀Gamety Monthly Run I is LIVE on Zealy!
Another chance to win $500 in $GTY!
🏆 Top 20 Zealy users will be rewarded:
🥇 1st Place – $75
🥈 2nd-10th – $30 each
🥉 11th-20th – $16 each
Don’t wait! Complete Zealy tasks now and climb the leaderboard!
#Rewards will be distributed 1 month after the campaign ends.
🔗 Join now: https://zealy.io/cw/gagentai
🔈Don’t miss this $GTY Era/ 🕊Tweet
📎Important Links:
$GTY Dextools|Website | X | Chat (FULL) | Indonesian Chat | African Chat | Vietnamese Chat | CIS Chat | Discord | Announcement | YouTube | Medium | New Bot | $GTY Staking | $GTY Coinstore
💎💎PROXIMA AIRDROP💎💎
✅INSTANT CLAIM $78 ✅
PROXIMA Chain ( PXM )
🔥We are happy to announce PROXIMA Chain #airdrop session!💎
💰 Claim : 78 ( PXM )
💳 Claim 78PXM for the first 15,000 people.
👥 Invite People to get 35% BNB and 65% PXM on Every Airdrop and Presale.. Referral NO LIMIT
🔆Claim or Purchase before April 30, 2022!
Copy link: 🔗https://proximachain.art/#presale
-BSC BEP20
-Contract: https://bscscan.com/token/0x0Df53b771A951798a6F5F909238E901b2c997369
We will cooperate with @PancakeSwap , @binance and @CoinMarketCap on the market launching.
💰 Don’t miss this chance to earn lucrative #rewards!
🎉PROXIMA AIRDROP $178IS LIVE
✅INSTAN CLAIM $178✅
PROXIMA Chain ( PXM )
🔥We are happy to announce PROXIMA Chain #airdrop session!💎
💰 Claim : 78 ( PXM )
💳 Claim 78PXM for the first 25,000 people.
👥 Invite People to get 35% BNB and 65% PXM on Every Airdrop and Presale.. Referral NO LIMIT
Claim or Purchase before March 30, 2022!
Copy link: 🔗https://www.proximachain.art/?ref=0x000000000000000000000000000000000000dead
-BSC BEP20
-Contract: https://bscscan.com/token/0x0Df53b771A951798a6F5F909238E901b2c997369
We will cooperate with @PancakeSwap , @binance and @CoinMarketCap on the market launching.
💰 Don’t miss this chance to earn lucrative #rewards!
🔥BIG AIRDROP🔥
✅INSTANT CLAIM $200 ✅
TetherMeta ( MUSD )
🔥 TetherMeta #airdrop session!💎
💰 Claim : 200 ( MUSD )
💳 Claim 200MUSD for the first 10,000 people.
👥Referral to get 25% BNB + 75% MUSD per Airdrop and Buy. Referral NO LIMIT !
🔥Listing Price: 1 MUSD = 1 USD
Liquidity will add on the Pancakeswap exchanges on May 17, 2022
Claim or Purchase before May 17, 2022!
Copy link: 🔗https://tethermeta.art/?ref=0x000000000000000000000000000000000000dead
-BSC BEP20
-Contract: https://bscscan.com/token/0x1C3aa9E4c13443D009f64F5480a5D733D4b540e0
💰 Don’t miss this chance to earn lucrative #rewards!Julia Bram, [19/03/2022 01:33]
[ Photo ]
🔥BIG AIRDROP🔥
✅INSTANT CLAIM $200 ✅
TetherMeta ( MUSD )
🔥 TetherMeta #airdrop session!💎
💰 Claim : 200 ( MUSD )
💳 Claim 200MUSD for the first 10,000 people.
👥Referral to get 25% BNB + 75% MUSD per Airdrop and Buy. Referral NO LIMIT !
🔥Listing Price: 1 MUSD = 1 USD
Liquidity will add on the Pancakeswap exchanges on May 17, 2022
🔥BIG AIRDROP🔥
✅INSTANT CLAIM $200 ✅
TetherMeta ( MUSD )
🔥 TetherMeta #airdrop session!💎
💰 Claim : 200 ( MUSD )
💳 Claim 200MUSD for the first 10,000 people.
👥Referral to get 25% BNB + 75% MUSD per Airdrop and Buy. Referral NO LIMIT !
🔥Listing Price: 1 MUSD = 1 USD
Liquidity will add on the Pancakeswap exchanges on May 17, 2022
Claim or Purchase before May 17, 2022!
Copy link: 🔗https://tethermeta.art/?ref=0x000000000000000000000000000000000000dead
-BSC BEP20
-Contract: https://bscscan.com/token/0x1C3aa9E4c13443D009f64F5480a5D733D4b540e0
💰 Don’t miss this chance to earn lucrative #rewards!
🩸THE BIG AIRDROP
✅INSTANT CLAIM $200 ✅
TetherMeta ( MUSD )
🔥 TetherMeta #airdrop session!💎
💰 Claim : 200 ( MUSD )
💳 Claim 200MUSD for the first 10,000 people.
👥Referral to get 25% BNB + 75% MUSD per Airdrop and Buy. Referral NO LIMIT !
🔥Listing Price: 1 MUSD = 1 USD
Liquidity will add on the Pancakeswap exchanges on May 17, 2022
Claim or Purchase before May 17, 2022!
Copy link: 🔗https://tethermeta.art/?ref=0x000000000000000000000000000000000000dead
-BSC BEP20
-Contract: https://bscscan.com/token/0x1C3aa9E4c13443D009f64F5480a5D733D4b540e0
💰 Don’t miss this chance to earn lucrative #rewards!
🎉THE BIG AIRDROP
✅INSTAN CLAIM $78 ✅
PROXIMA Chain ( PXM )
🔥We are happy to announce PROXIMA Chain #airdrop session!💎
💰 Claim : 78 ( PXM )
💳 Claim 78PXM for the first 25,000 people.
👥 Invite People to get 35% BNB and 65% PXM on Every Airdrop and Presale.. Referral NO LIMIT
Claim or Purchase before March 30, 2022!
Copy link: 🔗https://www.proximachain.art/?ref=0x000000000000000000000000000000000000dead
-BSC BEP20
-Contract: https://bscscan.com/token/0x0Df53b771A951798a6F5F909238E901b2c997369
We will cooperate with @PancakeSwap , @binance and @CoinMarketCap on the market launching.
💰 Don’t miss this chance to earn lucrative #rewards!
🔥Week 2 just dropped!
Climb the #HTX Dual Leaderboard for your shot at $1,500 in #rewards!
✔️ Follow @HTXCommunity + RT
📱 Join Telegram English + 2nd Group
📈 Trade on HTX
Inviters vs. Traders — who takes the crown this week? 👑
➡️Join Now!
✈️Telegram | ✖️X
✅Announcements📷Instagram