Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Whale NFT Expands to Solana via DYOR.io Community
#Whale#NFT
Whale has launched a new NFT bridge from TON to Solana, allowing users to seamlessly transfer and list NFTs on Magic Eden. The process is efficient and secure, with the added excitement of a suspenseful artwork reveal.
Source: link
@tonlines
🚨 A Bitcoin Whale Awakens After 14 Years!
Guess who made a comeback? A legendary Bitcoin whale, dormant for 14 years, just stirred. On their wallet sits a staggering 3,962 BTC, valued at a whopping $468 million.
Stay tuned with us for more crypto insights!
#btc#bitcoin#whale
🤑 $NOTCOIN — latest news
🥇 Notcoin is currently holding steady in the top 100 coins by capitalisation, ranking 55th. Daily trading volume has exceeded $500 million, making $NOT the 14th most traded coin among all existing coins.
💎 In the last 24 hours, the trading volume on Ston.fi in pairs with $NOT reached almost $2 million. The DEX team has prepared a guide for you on how to quickly buy or sell your Notcoin.
💎 As part of the test of the new w5 wallet standard, Tonkeeper has implemented the ability to send $NOT, without a TON on the wallet.
You can read more about w5 in our post.
💎 Strong projects on TON started actively burning $NOT, besides Not Foundation itself #Whale and #Catizen participated in this campaign. We continue to wait for more information from the team regarding the burning of $NOT coins from the bot.
💎 Coin owner rights have been revoked, making it so the total number of coins cannot be higher than the current number.
The token was added to Season 4 of The Open League, where it is now holding on to the prizes.
The team's immediate plans:
✔️Referrals (friends) will give you % of what they earn.
✔️PlatinumPlatinum and gold will get access to exclusive presales.
✔️ProjectsProjects and companies will be able to activate boosts without Not Foundation participation, which will speed up the addition of new tasks many times.
Channel: Whale Tank crypto
Members: ~18.19K
💢 Username: @whale_tank_crypto
Description:
The only channel run by real whales. We can guarantee you nobody else will ever get close to the trading volume in our pumps and signals…
Elevate your trading #journey ,
🏷 Tags: #crypto_fx_trading
#crypto#trading#signals#whale#bitcoin
https://lve.to/6dzu2j8pae
🌎 Sperm whales use a form of vocal “click” codes called codas to communicate within social groups. Each group has its own dialect of codas, with some sequences unique to specific clans. Adult whales use these patterns to maintain social bonds—individuals can be identified by their group’s coda “accent.” ✨
#whale⚡#communication⚡#animalbehavior⚡#bioacoustics
👉subscribe Interesting Planet
👉more Channels
🌴Whale: Claim Update Extended by Month...
wen TGE sir?
Guys, we have "alarm for +30 days" again. We were waiting for the Swap button, kept champagne in the fridge — but the timer was updated again... #$%^&* We understand, we are also a bit upset 🐸
Why does this happen?
As Whale reports, there are still 753 billion mWhale tokens are still in the game. Let us recall that according to tokenomics, 10% of the total emission of $Whale is intended for the community. In order for all these tokens to pass into our hands, the claims (and farming) were extended. The date of the TGE itself has not yet been announced.
What's the plan?
It's still the same: farm and claim as many tokens as possible, not giving the timer a chance to extend again, and we break into TGE with an even more impressive balance.
🪙
Patience and a collective sigh, friends... Let's stick together and keep our sense of humor
🤗
🤗
🤗
#WoW#Claim#Airdrop#Whale