Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Tonnel Network: TVL Reaches New Heights
#Tonnel#TVL
Tonnel Network reports a significant milestone with its Tonnel GiFi project reaching nearly $650,000 in Total Value Locked (TVL).
Source: link
@tonlines
Hipo Announces Season 4 DAO Vote Authorization
#DAO#TVL
Hipo has officially authorized the Season 4 DAO vote, marking a new model where hTON holders receive HPO directly. This aligns rewards with TVL growth, enhancing long-term protocol value. The community is preparing to implement these changes and will announce the launch date soon.
Source: link
@tonlines
🙎♂️How much $BOMB is already staked?🏦
As of 10:00 UTC, June 11th, the total value of funds locked (TVL) is:
Total locked: 2,171,444,131 $BOMB
TON Network: 1,758,096,769 $BOMB
Kaia Network: 413,347,362 $BOMB
The staking interest is 1000%+ APR
📱 Staking in TON Bombie🪙
📱 Staking in Kaia Bombie Line
Staking pool addresses:
TON: EQB4rcrDIrRzkhqtTsMHG5ikABcHjcgdyJohkSPQczoTt8yj
Kaia: 0xd914E92059CE903b871414503BF7bE53daB40C45
#BOMB#Staking#TVL#TON
🎥Intervention de la présidente de Sos DonbassAnna Novikova à la TV Libertés
🗓️ Diffusion mercredi 30 août à 12h30
Sujets abordés :
▫️Conditions de vie des habitants du Donbass
▫️Convoi humanitaire d’octobre 2023
▫️Projets de l’association
▫️Annonce du projet de livre📕
#sosdonbass#missionhumanitaire#tvliberte#TVL
Total #TVL#DeFi and assets under management in the largest #US banks. The #DeFi sector is now in its infancy and accounts for a tiny fraction of the banking sector — data from #Cryptorank
💲Earn rewards on STON.fi
The Open League community incentives program is just getting started, with up to 1 million Toncoin (TON) ready to be distributed to TON Community this month. This is an opportunity you don't want to miss.
Follow these simple steps to participate:
1️⃣ Launch @ston_fi.
2️⃣ Connect your wallet.
3️⃣ Click the top right menu and select 'Pools' from the dropdown.
4️⃣ Select the pool you want to provide liquidity for.
5️⃣ Provide liquidity and farm LP tokens.
6️⃣ Review and confirm your transaction.
7️⃣ Keep an eye on your position as reward distributions are subject to rapid changes.
For a visual guide, watch the attached video
➡️ Start on @ston_fi now!
#guide#TVL#farming#LP
ALLO Raises $100M for RWAs
ALLO has successfully raised $100 million in funding, with plans to make real-world assets (RWAs) tradable. The project has achieved a total value locked (TVL) exceeding $2.2 billion. More details can be found at ALLO.
#ALLO#Funding#RWA#Tradable#TVL#Investment#Blockchain#Crypto
🚀 Saturn Stablecoin Protocol Achieves $40 Million TVL Within 24 Hours of Launch
PANews posted on X (formerly Twitter) that Saturn, the first stablecoin protocol based on the Strategy STRC framework, has successfully launched on the mainnet. Within 24 hours of its debut, the protocol's Total Value Locked (TVL) surpassed $40 million. Saturn's stablecoin, sUSDat, offers an annual yield of over 11.5%, underpinned by Bitcoin through the STRC framework.
#SaturnStablecoin#STRCframework#sUSDat#TotalValueLocked#TVL#Stablecoin#Crypto#Bitcoin#DeFi#BTC
🚀 Solstice Finance Expands DeFi Asset Management with eUSX Growth
Solstice Finance is advancing decentralized finance (DeFi) asset management beyond single-strategy vaults, according to Tiger Research. The platform's eUSX has reached approximately $360 million in total value locked (TVL). According to NS3.AI, Solstice is currently operating eUSX and is preparing to launch strcUSX and oUSX. However, the platform still encounters challenges related to on-chain profit verification, funding-fee volatility, and team execution risk.
#DeFi#SolsticeFinance#AssetManagement#eUSX#TVL#Blockchain#Crypto#DecentralizedFinance#FinanceInnovation
[9 Mar to 15 Mar] DWF Crypto Snapshot
Our latest #crypto report by DWF Labs Managing Partner Andrei Grachev is up.
Here's your weekly round up 💫
💠 Global Institutions Continue To Build #Web3 Partnerships Despite Market Volatility
💠DWF Labs Unlocks The Potential Of Decentralized #Advertising With Latest Investment Round in WOM Protocol
💠DWF Labs Concludes Investment In Orbs Via US$10M #Token Sale
💠Investments Into #DeFi Increased Despite The #Bear Market In 2022, Says CoinGecko
💠DWF Labs Successfully Participates In Tonstarter Seed Funding As A Key #Investor
💠Bifrost Finance (PILAB Technology, Inc. (BIFROST)) Sees A Jump In #TVL After Launching 5.0 #Community Campaign
💠DWF Labs Drives Lending #Utility Via Its Latest #Partnership with LEND
Full read here.
Missed last week's snapshot? Read here.
Follow us on Medium here.
Stay up-to-date on the latest DWF Labs updates:
Website| Twitter | Linkedin | Telegram