Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
#OFFTOPIC - Il ministro dello Sviluppo economico Giancarlo Giorgetti ha confermato le voci sulla trattativa con Intel per la produzione di microchip in Italia, ma la pubblicazione della notizia “non giova”.
“Sì - ha detto rispondendo alle domande dei giornalisti, all’ambasciata d’Italia a Washington - la trattativa c’è, ci sono stati una serie di incontri, ma credo che sarebbe stato meglio se queste voci non fossero uscite. La riservatezza aiuta in questi casi”.
@amiciapple
#OFFTOPIC — Jeff Bezos passerà il testimone come amministratore delegato di Amazon a Andy Jassy nel terzo trimestre. Bezos diventerà presidente esecutivo.
✍🏻@amiciapple
If there is one thing you should know about me, it is this: I am quite big on word games, not necessarily puns — just a normal play of fancy words. There's just something satisfying about throwing around big words like "Tell me about it".
#OffTopic
#OffTopic
¿Creen que se haga una tercer guerra?
O si se logre detener a tiempo todo esto?
Y ojo, no me refiero a quizá guerra con armas y bombas nucleares
Presiento que va más por la onda cibernética
Porque Iran tiene un buen armamento en ese sentido
Iran confirma si habrá represalias contra USA
#offtopic
You want to congratulate someone on their birthday, but it occurs to you you are late, because their birthday was yesterday. 😅
What phrase would you use to wish this person a happy birthday?
The answer is Happy Belated Birthday!
𓂃◗🏄♀️10COSAS PARA HACER ANTES DE QUE ACABE EL VERANO 🪸. . Ꮺ
1. Termina un libro en tus lista de pendientes
2. Haz un picnic con tus amigos
3. Visitar un acuario
4. Sentarte en un parque a leer o dibujar
5. Aprender crochet
6. Remodelar tu habitación o decorarla
7. Ver o leer "Call me by Your Name"
8. Noche de juegos de mesa en familia
9. Hacer una cápsula del tiempo con tus amigos
10. Resolver un puzzle o rompecabezas
⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ
para más 𓂃◗ @apuntes_digitales
#offtopic#ideas
⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ
🤳 Social Media Dopamine Loop — Introduction
❗️Disclaimer: I am not gonna dive deep into the biological origin and purposes of dopamine as a hormone. Writing this post I just wanna emphasize how dangerous it is to follow and crave dopamine without control.
What’s the dopamine loop after all? This article sums it up pretty well. In a nutshell, it is a constant seeking of small and fast dopamine portions (or hits) that bring us short-term pleasure. It can be sugary food or drinks, it can be sex, binge-watching Netflix, playing video games, or even simple human interactions.
🤯Fun Fact: some scientists and writers were deliberately limiting their interactions with other people in the first part of the day in order to stay focused and not be distracted by peoples’ faces. Such an extreme approach comes from the fact that humans are extremely susceptible to faces. It takes a lot of our “RAM” to analyze and understand other human beings based on their facial expressions. So in order to perform at the highest, they made such sacrifices.
Coming back to dopamine. The main problem with such dopamine hits is that they can be achieved pretty effortlessly, without working hard to attain them (and I am not saying that in order to enjoy something you should “deserve” it only by working hard). ☹️
Let’s have a step back for a while and imagine how it all looked like thousands of years ago. Obviously, we won’t compare the lifestyle of people living then and now. The basic brain functions and frameworks, however, haven’t changed much since then. 🧠
What we need as humans basically are 2 things: calories and bits of information. The first ones feed our body and brain in order to function, and the second ones are crucial for our brain and therefore for our survival. How? Our brain is an extremely energy-consuming organ since it constantly gathers data around us, analyses it, and makes decisions that, at that time, were crucial for our survival.
🏹 From that standpoint, in order to get enough calories, you had to hunt. Hunts can be extremely long and unsuccessful. Once you get it you should start thinking about getting more later. Total pain in the a**, to be honest. Same with bits of information — we are especially receptive to visual clues, movements, and changes in the landscape in order to detect potential predators, food, etc. We are simply wired that way which enabled us to survive till that day. All this brainwork performed by us is exhausting. The same behavioral and neural patterns apply today.
What does it mean nowadays? Neither of these 2 resources is scarce now. Food — almost unlimited access. It’s nothing compared to thousands of years ago. Information — all around us. It’s actually overwhelming. No wonder obesity is taking over in developed countries and people are suffering more and more from depression, anxiety, and lack of energy. Like it or not, we (humanity) unconsciously broke the pattern that provided us with a healthy existence.
🍟 Funny enough, we actually can stop eating — that’s good news because otherwise we die or become less attractive mate partners. This mechanism works pretty well (on the other hand, given the amount of free porn and 0 effort to get sexual arousal I am not sure about that). However, when it comes to information therewas no need for evolution to develop a mechanism that would stop us from getting more information. I mean, why would you want that, right? More information means more chances of survival. Noone however expected that information will become available on THAT scale. Which has led, ironically, to disrupting our existence instead of improving it (apart from the overall civilizational progress, I mean).
📱So now, why can’t I stop scrolling on my app feeds? This question is connected to another one: why am I constantly in a bad mood, having depression or anxiety?
I am gonna cover some tips in the next post since it’s gotten pretty big already. Let’s collect 20 “🔥”, so I will see if you liked the post.
To be continued 🔜
#TooDeep
#OffTopic
#offtopic#CrazyEnglish
English is crazy: it's one of the languages where 'there is only so much we can do' means the same thing as 'we can't do much'.
@ieltsulugbeks