Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
EVAA Protocol: Temporary Suspension of stTON in Main Pool
#protocol#liquidity
EVAA has temporarily suspended the use of stTON as collateral in its Main Pool due to reduced market liquidity. Existing positions remain unaffected, but users must repay active loans before withdrawing stTON. The measure is temporary and will be lifted once liquidity conditions improve.
Source: link
@tonlines
🔤🔤🔤🔤🔤🔤🔤
Guys, some of you already heard about testnets, some of you not.
We would like to introduce you the first one called, Humanity protocol.
You need to claim your reward every 6 hours without clicking, entering combo and etc.
$RWT token is already trading.
Join humanity protocol👉link
#Testnet#Humanity#Protocol
DWF LABS makes another move to consolidate its position as one of the world’s leading Market Makers in #crypto, through a secondary investment in the MXC Foundation www.mxc.org - The MXC Foundation is the steward of the MXProtocol and the #MXC token. The MXC #token is listed on the world’s top exchanges, and starting on August 31st, MXC can be traded on Coinbase. DWF Labs made a multi-million dollars secondary market #investment in the MXC tokens and has been appointed as Market Maker.
#web3#marketmaking#protocol
🚀 StarkWare Researcher Proposes Complex Bitcoin Transaction Scheme
StarkWare researcher Avihu Mordechai Levy has introduced a Bitcoin transaction scheme that aims to circumvent the need for a protocol change. According to NS3.AI, the proposed method involves solving a pre-broadcast puzzle, which would necessitate approximately 70 trillion attempts. Levy characterized this design as a last-resort solution due to its significant computational demands, large transaction size, and potential relay-policy challenges, all of which could hinder scalability.
#StarkWare#Bitcoin#transaction#AvihuMordechaiLevy#protocol#computationaldemands#scalability#relaypolicy#BTC
Bitcoin Dominates Market with Huge Gains
Tesla's bitcoin holdings surge to $1.076 billion, boosting GAAP revenue by $600M. 🎉 The Sei Foundation launches a $65M fund for decentralized science startups, while GMCI unveils an index for US crypto protocols. Notably, Texas announces plans for a Bitcoin Reserve.
Read more about Tesla's valuation increase here. Explore the Sei Fund details here and GMCI's index here.
#Bitcoin#Tesla#DeSci#VC#Crypto#Funding#Texas#Cryptocurrency#Investment#MarketTrends#GMCI#Sei#Startups#Blockchain#Protocol#Accounting#Finance#Legislation#Innovation#CryptoProtocol
Ethereum Rollback Not Feasible, Developer Warns
Ethereum developer Tim Beiko cautions against rolling back the Bybit attack, citing potential widespread disruptions and significant costs exceeding $1.5 billion. This attack does not breach Ethereum protocol rules unlike the 2016 TheDAO incident. Additionally, a Bybit address transferred $48 million to Galaxy Digital and FalconX, acquiring 34,800 ETH shortly before depositing it back into Bybit.
Read more: Ethereum rollback debate and Bybit address transactions
#Ethereum#Bybit#Crypto#Blockchain#DeFi#News#Investment#ETH#GalaxyDigital#FalconX#TimBeiko#CZ#KanyeWest#Polychain#OTC#Transaction#Security#Protocol#Rollback#Market#Analysis
🚀 Polymarket to Upgrade Protocol and Launch pUSD Token on Polygon
Polymarket has announced plans to enhance its protocol and introduce pUSD, an ERC-20 collateral token on the Polygon network, fully backed by USDC. According to NS3.AI, the upgrade aims to lower gas costs and minimize failed trades. The platform intends to open-source the smart contracts next week and will initiate a bug bounty program to ensure security and reliability.
#Polymarket#Upgrade#Protocol#pUSD#ERC20#CollateralToken#Polygon#USDC#GasCosts#FailedTrades#OpenSource#SmartContracts#BugBounty#Security#Reliability
#java#bedrock#bedrock_edition#bedrock_to_java#bungee#fabric#geyser#geysermc#hacktoberfest#java#java_edition#minecraft#minecraft_bedrock_edition#packet#pe#protocol#proxy#spigot#translator#velocity
Geyser is a free tool that lets you play Minecraft across different versions by connecting Minecraft Java Edition servers. It works by translating data between the two game versions, enabling cross-platform play on devices like Windows, iOS, Android, and consoles. You can install it as a plugin or standalone, and it supports recent Minecraft versions. This means you can join Java servers even if you only have Bedrock Edition, expanding your multiplayer options without needing a separate Java account if you use the Floodgate plugin. It’s great for seamless crossplay but may have some minor limitations due to game differences[1][2][5].
https://github.com/GeyserMC/Geyser