Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🎧⤴
Ethereum ETF Set to Ignite Prices – Could ETH Hit $4,500?
Monochrome Asset Management has filed to launch an Ethereum ETF in Australia under the ticker "IETH." If approved, the ETF will offer a regulated way for retail investors to buy into Ethereum, marking a crucial expansion of crypto products in Australia. Analysts predict this could push ETH prices towards $4,500, especially if Bitcoin continues its upward momentum.
Verse 1:
ETF drop, watch the markets shake,
IETH comin’, time to raise the stake,
Aussie brokers lined up, ready to go,
Regulated crypto, yeah, it’s the show.
Chorus:
Will ETH hit that 4-5-0-0?
Markets movin’ fast, now they wanna know,
Monochrome pushin’ for the big rise,
Crypto to the moon, no surprise.
Verse 2:
Bitcoin’s on fire, aim for that 100K,
Ether right behind, it’s a bull run day,
Dual-access cash flow, simple as can be,
Australian retail gonna stack that ETH, see?
Chorus:
Will ETH hit that 4-5-0-0?
Markets movin’ fast, now they wanna know,
Monochrome pushin’ for the big rise,
Crypto to the moon, no surprise.
Bridge:
Hold tight, watch that price climb high,
Regulated ETF, no more askin’ why,
Cash or in-kind, take your pick,
Ethereum’s future, man, it’s lookin’ slick.
Verse 3:
From Bitcoin to ETH, it’s all on track,
Regulators here, no more lookin’ back,
Australia leads, yeah, they’re paving the way,
Crypto in the mainstream, here to stay.
Chorus:
Will ETH hit that 4-5-0-0?
Markets movin’ fast, now they wanna know,
Monochrome pushin’ for the big rise,
Crypto to the moon, no surprise.
#EthereumETF
#CryptoInvestment
#TONCryptoNewsRapStyle
🎧@toncoin_rap
🚀New Listing on SLEX: Welcome 1Inch!📈
✨We're happy to announce that 1Inch (1INCH\USDC & 1INCH\USDT) is now listed on the SLEX platform! Take advantage of trading 1INCH against USDC and USDT on the spot market starting today.
📊Whether you're planning to HODL or incorporate 1Inch into your diversified portfolio, SLEX offers you the perfect opportunity. Employ strategies like Dollar-Cost Averaging (DCA), long-term holding, or diversification to optimize your investment.
🌟Join SLEX Centralized Exchange, trade 1INCH/USDC & 1INCH\USDT on spot market and boost your earnings🌐
#SLEXExchange#1InchListing#SpotMarket#CryptoInvestment
Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🔖McHenry urges Senate to pass FIT21 crypto bill before election
The United States House’s widely positive vote on the crypto-regulating FIT21 bill should be “a wake-up call” to the Senate to quickly pass it, says Rep. Patrick McHenry 💬
#Cryptotrader
#Cryptotwitter
#Cryptoinvestment
#Cryptocurrencyexchange
🚀 Arthur Hayes Increases HYPE Holdings After Three-Month Hiatus
Arthur Hayes has made a significant move in the cryptocurrency market by purchasing 26,022 HYPE tokens, valued at approximately $1.1 million, after a nearly three-month break. According to BlockBeats, this acquisition brings his total holdings to 247,334 HYPE tokens, worth around $10.44 million, with an unrealized profit exceeding $2.5 million.
#ArthurHayes#HYPEHoldings#Cryptocurrency#CryptoMarket#BlockBeats#CryptoInvestment#HYPETokens#UnrealizedProfit
🚀 Bitcoin ETFs See Strong Inflows as Market Interest Grows
US spot Bitcoin ETFs experienced significant net inflows exceeding $786 million last week, marking their most robust performance since February. According to NS3.AI, BlackRock's iShares Bitcoin Trust attracted approximately $612 million. Meanwhile, Morgan Stanley's newly launched MSBT fund garnered around $46 million within its initial three trading days.
#Bitcoin#ETFs#BlackRock#MorganStanley#CryptoInvestment#MarketInterest#MSBT#iShares#Inflow#BTC
🚀 Tok-Edge Plans Institutional Crypto Hedge Fund with $100 Million Target by 2026
On April 12, digital asset financial services company Tok-Edge announced its intention to launch a crypto hedge fund aimed at institutional investors. According to BlockBeats, the fund seeks to raise $100 million in its first round by 2026, with a long-term goal of establishing a compliant infrastructure for institutional crypto asset allocation. The initial fund size is set at $21 million.
Veteran traditional finance investor Marcus Meijer and his investment alliance are backing the fund, with plans to contribute $10 million as cornerstone investors.
#TokEdge#cryptohedgefund#institutionalinvestors#digitalassets#cryptoinvestment#MarcusMeijer#investmentfund#blockchain#crypto
🚀 Strategy Requires 2.05% Annual Bitcoin Growth to Sustain Dividends, Says Michael Saylor
Michael Saylor has stated that Strategy needs an annual Bitcoin growth rate of 2.05% to cover its preferred stock dividends without the need to issue new common shares. According to NS3.AI, Strategy's dashboard indicates that the company holds 766,970 BTC, providing approximately 48.7 years of dividend coverage at the current reserve levels. The current annual yield for STRC stands at 11.5%.
#Bitcoin#MichaelSaylor#STRC#Dividends#CryptoInvestment#Cryptocurrency#BitcoinGrowth#PreferredStock#InvestmentStrategy#BTC
🚀 Grayscale's Q2 2026 Asset Consideration List Includes TON and TRX
Grayscale has unveiled its Assets Under Consideration list for the second quarter of 2026, highlighting several notable cryptocurrencies and projects. According to NS3.AI, the list features prominent names such as TON, TRX, Hyperliquid, and CELO. Additionally, it includes ENA, Worldcoin, Wormhole, and projects like MegaETH, Nous Research, and Poseidon. This announcement reflects Grayscale's ongoing evaluation of potential assets for inclusion in its investment products.
#Grayscale#Q22026#TON#TRX#Hyperliquid#CELO#ENA#Worldcoin#Wormhole#MegaETH#NousResearch#Poseidon#Cryptocurrency#Blockchain#CryptoInvestment