Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
➡️ UXUY Wallet
✅ PLAY NOW: https://t.me/UXUYbot/app?startapp=A_452308012_inviteEarn
Invested by BinanceLab 👈
Ends on January 10 ⛔️
$10.2M in funding successfully raised 🟢
1️⃣Securely store your private key
2️⃣Complete all tasks
3️⃣ Claim rewards every 3 hours
👍 UXUY: Don’t forget to back up your seed phrase!
❓ "Not your keys, not your crypto!"
👉 The Seed Phrase Backup Task is live!
Complete the backup and claim your reward of 800 $UP!
#UXUY
🪙UXUY Wallet: Mysterious Airdrop
When? TOMORROW, March 11, the project on Binance Labs investments #UXUY Wallet launches distribution, but there is an important condition:
✅UXUY wallet in Telegram needs to be created today!🔥
What needs to be done?
✔️ Hurry up to create a wallet before March 11 00:00 UTC.
✔️ Tell your friends — let them get a drop too!
✔️Follow the news!
☝️Create UXUY wallet now!
🥰Good morning fams! We are pleased to announce that UXLINK Mini App is live on LINE , now invite your friends on Line to join #UXLINK can get 10,000,000 #UXUY points reward!
In UXLINK's "One Account, One Gas" roadmap, $UXLINK will be the universal gas token for users who interact with different blockchains, and LINE and Kakao Talk will be important pillars of social platforms, will keep build and keep our community updated.
Super Airdrop from UXUY Wallet
#UXUY, incubated and supported by 🤑 Binance Labs, is launching the 2025 UXUY Points ($UP) #Airdrop!
🗓️ Dec 27, 2024 — Jan 10, 2025
How to join?
Invite three or more friends using your unique referral link
✅Go to the UXUY Earn Center
✅ Click on Tasks
✅ Complete them to earn UXUY Points ($UP)
🎁Join the event now and earn 2,025 $UP per user!
🔠🔠2025 New Year Special Airdrop Event ends in just 2 days!
🔣 Users who successfully invite 3 friends during the event period (December 27, 2024 — January 10, 2025) will receive an exclusive bonus of 2,025 $UP!
🔠🔠 Don’t miss out — get in there and rack up more $UP before it’s over!
#UXUY#wallet#airdrop
UXUY Wallet: Redefining Cross-Chain DeFi
UXUY is a platform (wallet and DEX) that provides tools and solutions for DeFi, focusing on multi-chain transactions and interoperability.
The main focus of the project is to facilitate the process of exchanging assets between different blockchains (cross-chain), with an emphasis on security, speed and convenience.
The project raised $10.2M in a funding round from well-known funds such as Binance Lab, KuCoin Ventures, MEXC and others.
Key features of UXUY:
1. Multi-chain compatibility: The platform supports interoperability between multiple blockchains, including Ethereum, BNB Chain, Polygon, Arbitrum, Avalanche and 🤑 TON.
2. Decentralization: Users retain full control over their assets as transactions are conducted directly through smart contracts, eliminating intermediaries.
3. Intuitive Interface: UXUY is focused on making DeFi easier for users, including a simplified asset exchange process.
4. Focus on Security: State-of-the-art security mechanisms, including multi-layered transaction verification architecture, are used to protect user funds.
UXUY Wallet Token – $UP
The $UP token is a key element of the UXUY ecosystem. It will be used to pay exchange fees, provide access to premium platform features, serve as collateral in staking programs, and will also become a tool for DAO governance.
The reward program has allocated 100 million UP, which will be distributed among the most active UXUY Wallet users.
🎁Complete tasks in the mini-app
#uxuy#dex#airdrop#binance
#Reminder UXUY WALLET
💎A project followed and supported by #Binance laps.
👀It has received high investments and its infrastructure is solid. The listing will probably not be extended.
It conflicts with the logic of Claim Every 3 Hours.
Link:⤵️
JOIN NOW https://t.me/UXUYbot/app?startapp=A_452308012_inviteEarn
⛏#uxuy#wallet#binancelaps
January Listing 🔥
✅#Nodepay: 6 January
✅#MomoAi: 6 January
✅#Xterio: 8 January
✅#Sidekick : 8 January
✅ $Vertus :13 January
✅#Seed : 15 January
✅#Xcoin : 20 January
✅#Tapswap : 23 January
✅#Wcoin : 25 January
✅#CommunityGaming : 28 January
Unofficial Listing
✅#PAWS
✅#UXUY
✅#Yuligo
✅#MemeWar
✅#DuckChain
✅#Celia
Stay connected