Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
STON.fi (Telegram)
🗿Impermanent Loss Protection: 2322 STON Sent to Liquidity Providers
Stonfiers! We've distributed STON 2322 STON offset to liquidity providers in the STON/USDT pool for December 1-31. Check your wallets!
💎 Here's what you need to know:
• You can offset up to 5.72% of your impermanent loss.
• Monthly protection budget: $10,000.
• Max offset per user: $100 in STON tokens.
• Auto-crediting — no need to claim!
🚨Important: Users who provided liquidity in theSTON/USDTpool before January 1 will be protected from impermanent loss until January 31!
🔗Add Liquidity Now🔗
#protection#liquidity
DEX | Telegram DEX | Onboarding | Guide | Blog | All Links
🐣X🤖Discord🌐Reddit🌐LinkedIn📹YouTube🪨Join the Club
STON.fi: Impermanent Loss Protection for Liquidity Providers
#protection#liquidity
STON.fi has distributed 6546 STON tokens to liquidity providers in the STON/USDT pool for November, with up to 5.72% impermanent loss offset offered. Users who provided liquidity before December 1 will have protection until December 31, with a monthly budget of $10,000.
Source: link
@tonlines
STON.fi: New Round of Impermanent Loss Protection Starts Soon
#protection#liquidity
STON.fi reminds liquidity providers that the new cycle of impermanent loss protection for the STON/USDT V2 pool begins on May 1st. Only those joining the pool by then will be eligible for protection.
Source: link
@tonlines
STON.fi Update: IL Protection Sent to Liquidity Providers
#protection#liquidity
STON.fi has distributed 894 STON to liquidity providers in the STON/USDT v2 pool for March 1-31, offering up to 5.72% impermanent loss offset. With a monthly protection budget of $10,000 and a max offset of $100 per user, auto-crediting ensures no claiming is needed.
Source: link
@tonlines
¿Que puede hacer este bot?
@NewUsersMediaLimiterBot
Este nuevo bot que limitará el envío de medios a los usuarios que acaban de unirse al grupo durante los primeros 30 minutos, a menos que sean desmantelados manualmente por uno de los administradores, el bot no enviará ningún mensaje cuando el usuario ingrese.
Idiomas: italiano inglés
(Visto en @botsgram_cu)
#grupos#administración#protection
🌍 Earth's magnetic field acts like a protective shield, deflecting harmful solar wind and cosmic rays. This invisible force helps preserve our atmosphere and supports life on the planet. ✨
#magnetism⚡#protection⚡#atmosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Souveraineté Alimentaire : Les dirigeants de l’AES doivent mettre un terme à l'accord de libre-échange et de coopération, par le biais duquel les États de la région ouest-africaine s'engagent à libéraliser progressivement leurs marchés au profit des importations en provenance d'Europe.
Il est essentiel de prioriser le renforcement des moyens et du soutien en faveur de nos agriculteurs locaux, plutôt que de continuer à inonder notre continent avec des denrées alimentaires européennes de qualité souvent médiocre, entraînant ainsi l'apparition de nouvelles maladies tropicales. #souverainetéalimentaire#Afrique#Protection
@egountchibehanzinTV
🇺🇿Oliy maktabda magistrlik dissertatsiyalari himoyasi bo‘lib o‘tdi
🔈 Joriy yilning 10\11-iyun kunlari Biznes va tadbirkorlik oliy maktabida 70411302 – Biznesni boshqarish (MBA) hamda 70411301 – Kichik biznes va xususiy tadbirkorlik (Biznes innovatsiyalar va tadbirkorlik) magistratura mutaxassisliklari tinglovchilari uchun Yakuniy davlat attestatsiyasi doirasida magistrlik dissertatsiyalari himoyasi bo‘lib o‘tdi.
🔼 Jami 23 nafar tinglovchi, jumladan Biznesni boshqarish (MBA) mutaxassisligi bo‘yicha 10 nafar, Kichik biznes va xususiy tadbirkorlik mutaxassisligi bo‘yicha 13 nafar tinglovchilar magistrlik dissertatsiyalarini muvaffaqiyatli himoya qilishdi.
👨🎓
📔 Magistrlik dissertatsiyalari O‘zbekiston Respublikasi Prezidenti huzuridagi Davlat boshqaruv akademiyasi kafedra mudiri, professor, Yakuniy davlat attestatsiyasi komissiyasi raisi D.Raximova hamda komissiya a’zolari tomonidan baholandi. Dissertatsiyalarni himoya qilish jarayoni ilmiy mubohasa yo‘sinida va yuqori talabchanlik bilan o‘tkazildi.
🌀Batafsil
#GraduateSchool#Protection#Dissertation#Work
🌐Web-site |
✅Telegram |
✅Facebook |
🌐Instagram
🔥 Сегодня
🔥 Вебинар PETYA, МАЙНИНГ, UEBA
📅 20 марта / 11:00 — 12:30 (время МСК) / онлайн
💵 Бесплатно
📝 Регистрация тут: https://goo.gl/1HJ68T
Как не повторить ошибок 2017-го и войти в 2018 год во всеоружии, заранее знать основные угрозы и как с ними бороться, на практических примерах расскажет руководитель экспертного отдела «Гарда Технологии» Роман Жуков.
🔗 Программа: https://goo.gl/1HJ68T
#security#cybersecurity#protection#онлайн
#go#attacks_prevention#detection#linux#protection#security
CrowdSec is an open-source security solution that helps protect servers from malicious IP addresses. It uses a community-driven approach, where users share information about threats they've faced, creating a shared blocklist to prevent attacks. CrowdSec's Security Engine can detect bad behaviors by analyzing logs and HTTP requests, and it supports multiple platforms. This system is fast, easy to use, and designed for modern infrastructures, making it a powerful tool for securing your systems against various threats. By using CrowdSec, you benefit from collective protection and can focus on real security issues.
https://github.com/crowdsecurity/crowdsec
@littleGuardianBot
Qué puede hacer este bot?
LittleGuardian fue creado como un bot para apoyar los esfuerzos de los administradores del grupo Telegram mientras luchaba con comportamientos antisociales y varios ataques contra los grupos o miembros del grupo.
Idioma: Inglés
(visto en @BotsGram_cu)
#antispam, #protection, #management, #groups, #filter, #welcome
Some Buddhists serve as soldiers even though Buddhism teaches non-violence. Soldiers can protect people, and Buddhism considers the intention behind actions. Actions that reduce suffering can be acceptable according to Buddhist ethics. Concepts like karma and skillful action are important. International humanitarian rules guide soldiers to act carefully. Being a Buddhist does not always mean being completely against war. Martial arts like Kung Fu also connect to Buddhism. They teach discipline, self-control, mindfulness, and protecting others. The goal is training the mind and body, not just fighting.
🕉️⚔️🥋
[Read more]
@googlefactss
#Buddhism#Ethics#Soldiers#NonViolence#Karma#Protection#SkillfulAction#KungFu#MartialArts#Mindfulness