Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
BIT x DWF Labs
Crypto Snapshot [3 Feb] 📰
Highlights:
🔸#Bulls Cautiously Optimistic About #Bitcoin’s Price Movement
🔸 US Debt Measures Will Become Bitcoin’s Boom
🔸 Strong #Institutional Support For Bitcoin Indicates Future Rally
Full read here.
Singapore Exchange Launches Bitcoin Futures
🔵 The Singapore Exchange (SGX) will launch perpetual Bitcoin futures by H2 2025, marking the first such product on a traditional Asian stock exchange. This move aims to attract major institutional players to the cryptocurrency market, expanding access and trading opportunities. 🔗 Read more: Bloomberg
#Bitcoin#Crypto#SGX#Futures#Investment#Asia#Finance#Trading#Blockchain#DigitalAssets#Market#Institutional#PerpetualFutures#CryptoMarket
Massive ETH Transfer to Coinbase Institutional
🚨 21,772 #ETH ($57.8M) transferred from unknown wallet to Coinbase Institutional. Details: Whale Alert
🔥 56,492,765 #USDC burned at USDC Treasury. Details: Whale Alert
🇺🇸 Standard Chartered anticipates $1.1 trillion in sovereign wealth funds increasing #Bitcoin investments. More updates coming!
#ETH#USDC#Bitcoin#WhaleAlert#Strategy#MSTR#Crypto#Finance#Investment#Market#SovereignWealthFunds#Trading#Ethereum#Institutional#News#Updates#VC#Blockchain
Bitcoin Predicted to Reach $200K by 2025
CryptoQuant analysts forecast Bitcoin may hit $200,000 by 2025. Driving factors include:
✔️ $520 billion institutional capital influx
✔️ Easing monetary policy and favorable crypto regulation
✔️ Historical price surges in the final year of four-year cycles.
For more details, visit Forklog News.
#Bitcoin#Crypto#Market#Analysis#Forecast#Investment#Institutional#Regulations#BullMarket#Trends#Finance#CryptoNews#Blockchain#Tech#Economy #2025 #Capital#Growth#QuantAnalysis#Traders#Volatility
BitGo Considers IPO in 2025
Crypto custodian BitGo Inc. is exploring an IPO, potentially listing in H2 2025 amid positive regulatory climate. The company raised $100 million in 2023, increasing its valuation to $1.75 billion. This move aligns with growing institutional interest in crypto. Read more: Bloomberg
#Crypto#IPO#BitGo#Blockchain#Investment#MSTR#Profit#Custody#Regulation#Market#Financial#Valuation#Institutional#Assets#Saylor#Trading#News#Tech#Finance#VC
KTON Targets $6.12B Liquid Staking Market
KTON, a liquid staking protocol by TONX, is set to launch V1 in February, aiming for a significant market expansion in the $6.12 billion liquid staking sector on TON. With Telegram's full support for TON, KTON plans to allow users to stake TON while earning KTON tokens, offering institutional-grade security. The project sees a potential growth from the current liquid staking market of $377 million to match Ethereum's levels, aiming for an 18-fold increase. KTON integrates with leading DEXs like Ethena and Curve Finance to provide flexible income strategies in the DeFi space.
#KTON#TON#Staking#LiquidStaking#Blockchain#DeFi#Crypto#Institutional#Investment#Tech#Finance#Ethereum#Telegram#VC#MarketGrowth#Solana#TONX#Security#Innovation#Ecosystem
Binance Hits 250M Users, Record Stats
Binance reports over 250 million registered users by year's end, a 47% increase. Platform processed 4.44M requests/second; VIP users up 116%, institutional users up 97%. Internal compliance team expanded to 650 experts. Read more
US government clear to liquidate 69,000 Bitcoins (valued at $6.5B) seized from Silk Road. This follows a promise by the new administration not to sell the Bitcoins. Read more
#Binance#Bitcoin#Crypto#Users#VIP#Institutional#Compliance#SilkRoad#Seizure#Finance#USGovernment#AnnualReport#MarketCap#Trading#Blockchain#Investments#Tech#DigitalCurrency#News
Bybit Under High Withdrawal Pressure
MEXC transferred 12,652 stETH ($33.75M) to Bybit's cold wallet. Bybit expected 64,452 ETH ($170M) in loan support from Bitget. An additional transfer of 11,800 ETH ($31M) occurred from Binance. Following a recent hack, Bybit recorded peak withdrawal levels, surpassing 350,000 requests; 99.994% have been processed.
Links: Porter Stansberry, Ben Zhou
#Bybit#MEXC#stETH#ETH#Crypto#Binance#Bitget#Bitcoin#Withdrawals#Whale#Finance#Hack#Blockchain#Investments#Market#Institutional#Debt#Liquidity#Trading#Assets#VC
Major USDC Burn & USDT Transfer News
🔥 50,000,000 #USDC burned at USDC Treasury. Full details here.
🚨 Nearly 500M #USDT transferred from #HTX to Tether Treasury, confirming strong liquidity movements.
🤑 MicroStrategy bought 258,320 BTC for over $22B in 2024, averaging $85,450 per BTC. Potential profit of $14B if BTC reaches $100,000. More info here.
🚀 Czech National Bank considers Bitcoin for reserve asset diversification. Details: link.
🔥 Total market cap for AI tokens approaches $17B, witnessing a 4% increase. Top tokens include #FET, #VIRTUAL, #AI16Z.
🔧 Solana developers aim to resolve scalability issues, targeting optimal performance as user base grows. Learn more here.
💡 Ripple partners with Chainlink to launch #RLUSD in DeFi, currently ranked 724 on CoinGecko with a market cap of $72.2M.
📉 Coinbase premium drops to a 12-month low, signaling potential short-term pressures for Bitcoin with analysts noting need for renewed institutional interest. More details here.
#USDC#USDT#MicroStrategy#Bitcoin#Crypto#Ripple#Chainlink#AI#DeFi#Solana#CzechRepublic#Liquidity#MarketCap#Investing#Institutional#Trends#CryptoQuant#RLUSD#VIRTUAL#FET#AI16Z