Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🎉 Let’s recap the 10 Lucky Stakers who snagged the first 10 TON in the 100 TON Daily Tycoon Launchpool!
1️⃣ CebuanoKing 🔵 ONUS BITS $X💠
2️⃣ Süleyman
3️⃣@Click_Mining
4️⃣ Arthur
5️⃣ Modzilla 🐔🐈⬛🎤 Firefox
6️⃣ SanMoTraz
7️⃣ Tuấn Anh 🇻🇳🐾
8️⃣ Em 🐔🍅🎤 C ^^
9️⃣ Pham Minh Nhan
🔟 Xaumarket
🔥 9 more days to go! Keep staking for your chance to win big 👉https://t.me/SingSing_TG_bot/app
👉#SingSingTycoon#TON#Launchpool
🚀 SingSing Launchpool: Mystic Garden is Live! 🎉
🌟 Stake $SING, Earn AURA – The In-Game Currency of Mystic Garden Game! 🌟
💰 Launchpool Overview:
- Total Rewards: 1,000,000 AURA
- Period: Nov 27, 13:00 – Dec 23, 12:59 (UTC)
💎 Staking Details:
- Minimum Stake: 500 $SING
- Maximum Stake: 20,000 $SING
- Rewards are settled every hour based on your staked $SING share.
🎮 What’s $AURA?
AURA is the in-game currency for Mystic Garden, used to unlock premium upgrades, enhance gameplay, and claim exclusive rewards.
Note: Mystic Garden Game is coming soon, grab the early bird chance to get AURA before game launching.
👉 How to Join:
1️⃣ Prepare your $SING tokens (at least 500 $SING to participate).
2️⃣ Stake your $SING in the Launchpool.
3️⃣ Get your AURA rewards automatically after Mystic Garden Game Launching!
Note: If you have not got $SING, easily buy at:
- BingX: https://bingx.com/en/spot/SINGUSDT/
- CoinEx: https://www.coinex.com/en/exchange/sing-usdt
#SingSing#MysticGarden#Launchpool
🔥 CHICK Launchpool is BACK! 🔥 Another 1,000,000 CHICK is coming your way!
🟡 Total Rewards: 1,000,000 CHICK
🗓 Period: Jan 15, 7:00 AM UTC - Feb 5, 7:00 AM UTC
🔒 Staking Limit: 500 $SING - 20,000 $SING
⏱️ Rewards: Settled hourly based on your $SING share
💰 Easily Buy $SING Here:
- BingX: https://bingx.com/en/spot/SINGUSDT/
- CoinEx: https://www.coinex.com/en/exchange/sing-usdt
- SingSing Mini App: https://t.me/SingSing_TG_bot/app?startapp=_wallet
- OKX Wallet: Guideline (https://t.me/singsingchannel/1088)
#SingSing#Launchpool#Chickizen
🌟 Big Reveal: Mystic Garden is Coming! 🌟
SingSing is launching a brand-new game, Mystic Garden, alongside an exciting Launchpool opened tomorrow Nov 27 - 13:00 UTC! 🚀
🎮What is Mystical Garden?
A magical game where you grow rare elemental plants, craft NFTs, and compete for leaderboard rewards while earning BNB and other rewards! 🌱💎
Stay tuned for more details—magic meets GameFi soon! ✨
#SingSing#MysticGarden#GameFi#Launchpool
🎤Announcement | Chat | X (Twitter) | Website | Game
🚨 LAST CALL! 🚨
Today is the FINAL DAY of the AURA Launchpool!
⏰ Pool closes at 13:00 UTC, Dec 23.
🌟 It’s almost harvest time—get ready to reap the rewards of your hard work! 💎
⏳ Don’t miss your chance to stake and earn!
#SingSing#AURA#launchpool
🎤Announcement | Chat | X (Twitter) | Tycoon Game
🚨 CHICK Launchpool has officially ENDED! 🚨
It’s time to CLAIM your rewards 🎁🔥
⏳ Don’t miss out—head over now and claim what’s yours!
👉 Link to claim
#SingSing#Launchpool#CHICK
⏳Reminder, $SING Stakers!
The CHICK Launchpool ends tomorrow, Jan 6! 🐥
🐣 Reward: 1,000,000 CHICK
🎯 Stake Limit: 500-20,000 $SING
⏳ Ends: 7:00 AM UTC - Jan 6, 2025
Don’t miss your chance to stake and earn before it’s gone. Let’s make these final hours count! 🚀
#SING#PlayToEarn#Launchpool
All Showdown #5 rewards have been distributed!🎉
Notifications have been sent to all accounts that received rewards—check yours now!
Got $SING? 💎 Don’t miss out on joining the Launchpool and making the most of it! 🚀
Join Launchpool Now: https://t.me/SingSing_TG_bot/app?startapp=_launchpool
#SingSing#ShowdownRewards#Launchpool
🌿 Curious about Mystic Garden? The wait is almost over... 🌟
✨ Be among the first to step into this magical world!
👉 Join AURA Launchpool now and secure your exclusive ticket to explore Mystic Garden!
AURA Launchpool 🔗https://t.me/SingSing_TG_bot/app?startapp=_launchpool
#MysticGarden#Launchpool#SingSingGaming
🚀 SingSing Launchpool: Tycoon Season 1 is Live! 🎉
🌟 Stake $SING, Earn $KARA – The In-Game Currency of Tycoon! 🌟
💰 Launchpool Overview:
- Total Rewards: 1,000,000 $KARA
- Period: Nov 22, 7:00 AM (UTC) – Dec 6, 6:59 AM (UTC)
💎 Staking Details:
- Minimum Stake: 50 $SING
- Maximum Stake: 2,000 $SING
- Rewards are settled every hour based on your staked $SING share.
🎮 What’s $KARA?
$KARA is the in-game currency for SingSing Tycoon, used to unlock premium upgrades, enhance gameplay, and claim exclusive rewards.
👉 How to Join:
1️⃣ Prepare your $SING tokens (at least 50 $SING to participate).
2️⃣ Stake your $SING in the Launchpool.
3️⃣ Watch your $KARA rewards roll in automatically!
Note: If you have not got $SING, easily buy at:
- BingX: https://bingx.com/en/spot/SINGUSDT/
- CoinEx: https://www.coinex.com/en/exchange/sing-usdt
🔥 Don’t miss this chance to boost your Tycoon gameplay – stake early for maximum rewards!
#SingSing#Launchpool#TycoonSeason1#GameFi
🚨 Sneak Peek! 🚨
🔥1,000,000 $KARA is within your reach! 💥
SingSing Launchpool: Tycoon Season 1 goes live this week! 🎮
💰 Stake your $SING and earn $KARA – exclusive rewards await!
Tips: Make sure you have $SING to join, If you have not got $SING, easily buy at:
- BingX: https://bingx.com/en/spot/SINGUSDT/
- CoinEx: https://www.coinex.com/en/exchange/sing-usdt
⏰ Mark your calendars – the countdown begins!
#SingSing#Launchpool#TycoonSeason1#GameFi
🚨 Attention, stakers! The CHICK Launchpool has officially come to an end! 🐥
📤 Don’t forget to claim your hard-earned rewards right now: https://t.me/SingSing_TG_bot/app?startapp=_launchpool
💥 This is just the beginning—get ready for the next Launchpool, where even bigger and better opportunities await!
Stay tuned and keep staking for more amazing rewards! 🔥
#SingSing#CHICK#Launchpool#Web3Gaming