Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Why am i so addled, i seek retort through this creation.
Can't understand a thing, anymore. I just need Salvation
What am i gonna gain, if anything, why do i need revelation.
I do just fine without mass, getting back to isolation?
Why is it so important, why look for identification?
Is it the curiosity or the fear of seperation?
There is inspiration, there is recreation, there is manipulation, sensation, violation & frustration but is there anything that's necessary? Is there any elevation?
I know it bothers none but please, tell me, where am i heading to, what is my destination?
#Snowy#review
I mutilate myself, no matter what i do.
Acting all spirit, i maim when I'm disregarded, when I'm passed over.
Acting all foul isn't my cup of tea either, i maim again, i incapacitate either way.
Being ignoble and or moral, both roads are noxious to me. What do i fancy then?
You blemish me, your bygones. I can't condone it. I can't strand you either. You, your, it impedes me, candidly but won't gash you by disclaim, renounce.... Won't? Well, can't is more apt, can't bestow to soar your agony.... But about my torment? I have nowhere to go, no door left open, I'm stuck, stuck with you. I'll dwell, I'll persist, that's what I've been doing, that's what i can keep up with. No possibility, either at whim or reluctantly, i have to adhere, no recourse.... I'd be thrusting here, i don't know the stretch, the extent, maybe perpetuity.
#review#Snowy
Why am i so addled, i seek retort through this creation.
Can't understand a thing, anymore. I just need Salvation
What am i gonna gain, if anything, why do i need revelation.
I do just fine without mass, getting back to isolation?
Why is it so important, why look for identification?
Is it the curiosity or the fear of seperation?
There is inspiration, there is recreation, there is manipulation, sensation, violation & frustration but is there anything that's necessary? Is there any elevation?
I know it bothers none but please, tell me, where am i heading to, what is my destination?
#Snowy#review
You were fire, i wasn't ice
I was supposed to but it wasn't nice
I was magma that was piquant
Why was our bond so highly turbulent?
The violent gesticulation of air around your flames
Wasn't any good for my fever but i got used to the games
We were bonded the way we weren't meant to be
Was it destiny, i wondered or was it our will that was the key
You're no good for me, i know, said she
But it was too late for her to be set in the world again like a bird, free
If we're meant to do it together, yes my love, we suffer like the way we suffered
You'd be the flame of my candle that demolishes my wax, he uttered
Afterall, diamonds dice diamonds, they are suited together
Shouldn't be befuddled with types different but stay where they belong, forever
#Snowy
#review