Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
👀Educational content, charity and newcomer-friendly tools: An insightful look into the inner workings of a global crypto exchange.
🛡Learn how BingX diverse trading options can help you manage risks and capitalize on opportunities.
#DigitalCurrency
#Cryptonews
#CryptoCommunity
#Cryptolife
🚀 Iran Utilizes Cryptocurrency for Strait of Hormuz Passage Fees
Iran is employing cryptocurrency to collect fees from ships passing through the Strait of Hormuz. According to NS3.AI, TRM highlighted that the rapid nature of digital currency transactions and their operation outside the U.S. banking system complicate efforts by the U.S. to freeze or block these payments in real time.
#Iran#Cryptocurrency#StraitOfHormuz#DigitalCurrency#Shipping#USSanctions#Blockchain
Massachusetts to Establish Bitcoin Reserve
Massachusetts Senator Peter Durant proposes a bill to create a Strategic Bitcoin Reserve. This aligns with initiatives in states like Oklahoma, Wyoming, and Ohio, driving a potential federal reserve plan via executive orders or legislative action. Full details here: Blockspace
#Bitcoin#Crypto#Blockchain#Finance#Investment#Legislation#DigitalCurrency#Innovation#Massachusetts#UTC VC
🚀 Quantum Safe Bitcoin Proposed to Resist Quantum Attacks
Avihu Levy has introduced a concept called Quantum Safe Bitcoin, which is a hash-based transaction design intended to withstand quantum computing attacks. According to NS3.AI, this proposal seeks to enhance Bitcoin's security without altering its fundamental rules. The estimated cost for implementing this design using cloud GPU computing ranges from $75 to $150. However, the complete transaction assembly and broadcast have yet to be demonstrated on the blockchain.
#QuantumSafeBitcoin#Bitcoin#QuantumComputing#Blockchain#Cryptocurrency#CyberSecurity#DigitalCurrency#CryptoInnovation#BTC
🚀 AI TRENDS | Xverse Launches AI-Driven Bitcoin Wallet for Enhanced Transactions
Bitcoin wallet Xverse has announced the introduction of its AI-powered Agentic Wallet, designed to facilitate payments, transactions, and fund management on the Bitcoin network. According to Foresight News, the wallet utilizes Spark for lightning payments and supports machine-payable APIs through MPP, featuring a fully self-custodial architecture.
#AI#Bitcoin#Cryptocurrency#Fintech#Wallet#Blockchain#Payments#MachineLearning#DigitalCurrency#BTC
🚀 Solana Developer Platform Launches Amid Growing Interest in Stablecoin Settlement
The Solana Foundation has introduced its Solana Developer Platform, marking a significant milestone for the network as it reaches 167 million monthly token holders. According to NS3.AI, this development comes as major financial entities like Mastercard are investigating stablecoin settlement on the Solana blockchain. Additionally, Worldpay and Western Union are exploring on-chain settlement and cross-border transfer capabilities.
In a related move, MetaMask has announced that its MetaMask Card now allows American users to spend Solana USDC at any location where Mastercard is accepted. This expansion of services highlights the increasing integration of Solana's blockchain technology into mainstream financial systems.
#Solana#Blockchain#Stablecoin#Crypto#DeFi#MetaMask#USDC#Fintech#CrossBorderPayments#DigitalCurrency#SOL
🚀 Russia Implements Full Ban on Crypto-to-Cash Exchanges
Russia has enacted a comprehensive ban on crypto-to-cash exchanges, marking a significant policy development in the region. According to NS3.AI, this move is part of a broader trend of regulatory changes across Asia, as countries continue to refine their approaches to cryptocurrency regulation. The ban is expected to impact the way digital currencies are traded and used within Russia, potentially influencing other nations in the region to adopt similar measures. This development is one of several key policy shifts observed in Asia this week, highlighting the evolving landscape of cryptocurrency regulation.
#Russia#Cryptocurrency#CryptoRegulation#CryptoBan#DigitalCurrency#Asia#PolicyChange
Avalanche Visa Card Launches Today
Avalanche has officially launched its Visa card to promote cryptocurrency adoption. The card allows users to spend crypto easily in daily transactions, integrating DeFi solutions. This move aims to bridge the gap between traditional finance and the digital currency landscape, enhancing user accessibility to crypto assets. Read more here.
#Avalanche#Crypto#DeFi#Visa#Blockchain#Finance#MassAdoption#Payments#DigitalCurrency
🚀 Swiss Banks Launch Sandbox for Franc-Pegged Stablecoin Testing
Six Swiss banks, in collaboration with Swiss Stablecoin AG, have initiated a sandbox project for a stablecoin pegged to the Swiss franc, set to operate until 2026. According to NS3.AI, the test involves an ERC-20 token on the Ethereum blockchain and will be conducted in a controlled live environment with transaction limits and a restricted participant pool. While the specific access terms and use cases have not been disclosed, an interim report is anticipated in the second half of the year.
#Switzerland#Banks#Stablecoin#Cryptocurrency#Blockchain#Ethereum#FinTech#DigitalCurrency#Sandbox#Finance#ETH
🚀 Authorities Freeze $12 Million in Cryptocurrency Crime Proceeds
Authorities from the United States, the United Kingdom, and Canada have collaborated in a cross-border operation to freeze $12 million in proceeds from cryptocurrency-related crimes. According to NS3.AI, the investigation specifically targeted phishing schemes, highlighting the ongoing efforts to combat cybercrime in the digital currency sector.
#cryptocurrency#cybercrime#phishing#lawenforcement#crossborder#digitalcurrency#crimeproceeds#NS3AI