Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
#session
🟧“TechWomen” va “UEnter” sizni STEM sohasida ayollar uchun imkoniyatlar haqidagi bepul mashg‘ulotga taklif etadi!
🗓 2024-yil 1-dekabr, 13:00 – 15:00
📍 “UEnter”
🟧 Bunda siz “TechWomen 2024” bitiruvchilarining muvaffaqiyat hikoyalarini tinglaysiz hamda dastur, jumladan ariza topshirish jarayoni va talablar to‘g‘risida ma’lumot olasiz.
Sessiya Silikon vodiysida mentorlik, kasbiy rivojlanish va aloqalar o‘rnatishga bag‘ishlanadi.
⭐️Havola orqali ro‘yxatdan o‘ting.
🟧 O‘z mahoratingizni oshirish imkoniyatini qo‘ldan boy bermang!
______
TechWomen and UEnter cordially invite you to a complimentary session on opportunities for women in STEM!
🗓 December 1, 2024, 1:00 PM – 3:00 PM
📍 UEnter
🟧 Discover inspiring success stories from TechWomen 2024 alumnae and gain information about the program, including application procedures and eligibility requirements.
This session will highlight mentorship, professional development, and networking opportunities in Silicon Valley.
⭐️ Registrationlink
🟧 Do not miss this opportunity to expand your professional horizons!
Telegram | Instagram | Facebook | Youtube | LinkedIn
Instant messaging apps review
I tested a lot & mulled on this for a while.
Our goal was something less centralized, more private & harder to take down or block.
BRIAR is good & with p2p modes to be censorship resistant if internet is cut, but you have to invite each user separately to a group which is a pain
XMPP is archaic & behaves like a traditional one to one messenger. Yes, groups are there but are more like texting groups & you can't tag or reply to anyone directly.
MATRIX is better but ends up being 3rd party centralized because hosting yourself is a hog, which means you're bound by that hosted server & all those rules, giving up your email credentials, getting possibly kicked off, etc. Matrix.org server started requiring email verification for instance.
Matrix doesn't encrypt metadata, your IP is visible to others in chats.
The last 2 require a hosted server somewhere for large groups to function properly, and so does SESSION since it too has no servers of it's own. But its way lighter than Matrix & can be hosted on a mediocre VPS (which I've done, I can pay, its cheap its fine). The added benefit of Session is everything is onion routed automatically, and there's zero identifying factors when creating an ID. No phone numbers, no emails, nothing. Restore that ID on a new device using a cryptic passphrase, or start a new one if you want.
Check out @Nogoolag room with SESSION:
http://chat.nogoolag.com/nogoolag?public_key=53b45de08520eb3af97933e9a4991e74e26972ee91cc94e6a05da03d956d4313
#im#session
Session plénière du #Forum économique oriental : les détails avec Antoine Cléraux
Le Forum économique oriental se déroule actuellement à Vladivostok en Russie. Son but est de promouvoir les investissements étrangers dans l'Extrême-Orient russe. Le point d'orgue de ce forum est la #session plénière, à laquelle a participé Vladimir #Poutine. Retour sur ces trois heures de débat avec notre envoyé spécial Antoine Cléraux.
RT en français
The library allows us to store user-specific data into a #session object.
The session object has a dict-like interface (operations like session[key] = value, value = session[key] etc. are present).
Before processing the session in a web-handler, you have to register the session #middleware in #aiohttp.web.Application.
https://github.com/aio-libs/aiohttp-session
6 Best Secure Messaging Alternatives to WhatsApp | Avoid the Hack – https://avoidthehack.com/best-secure-messengers
The content of your messages and the metadata associated with them should be secure and private. Unfortunately many messengers out there fail to do this.
Telegram operates in the cloud, and while this does have good portability across multiple devices and device types, the service provider (or anyone with access to the cloud server) could theoretically read them at any time with relative ease; Telegram stores messages on the third-party cloud provider's server.
According to Telegram’s privacy policy, the service itself logs IP addresses and phone numbers.
#Infosec#Session#SimpleXchat#Briar#Threema
#Element#Telegram#privacy