Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
#trending: Teenager who has autism waits an hour at Jurong East MRT Station with no train service, mum goes to his aid
"The problem was that he didn’t know what his next step should be. At the same time, he may have been hoping that the train would arrive later." Ms Lydiawati Ismail said of her son who has autism.
🚇https://tdy.sg/3NajJLe
@todayonlinesg
#trending: Father-daughter dance at competition goes viral, viewers say it made them cry or think of their own dads
They won a “special mention” medal and they were also the oldest and youngest participants in the open category, Mr Jay Sng said.
🤸♂️🧑🧒https://tdy.sg/3XkEgla
@todayonlinesg
#trending: S'pore woman's biggest culture shock living in Sweden? Many couples skip marriage even after kids
Ms Wynnette Yip said that she has been in a relationship with her Swedish partner for eight years and often faces questions from friends and family in Singapore on whether her other half was ever going to propose to her or was simply "wasting (her) time".
🇸🇪https://tdy.sg/3ZpFcHx
@todayonlinesg
#trending: 'Full-on racial harmony' — video of Chinese S'porean youths loving Tamil movie goes viral
Many netizens found it refreshing and heartwarming to see Chinese youths so thoroughly enjoying a film of a different language and culture, with users calling their reactions "cute" and "awesome".
🎬https://tdy.sg/3AQNKwP
@todayonlinesg
#trending: 'Completely drained' — British expat's tale of long hours in China's tech sector goes viral
Many social media users in China were amused to see a foreigner grappling with the demanding work culture in their country.
🇨🇳https://tdy.sg/4egs2Ry
@todayonlinesg
#trending: S'pore non-profit that staged TikTok video of man harassing woman sparks debate on when to step in to help others
TikTok users have lauded real-life passers-by who chose to intervene and help the woman, not realising that it was a staged incident. They said that it is important to look out for each other.
➡️https://tdy.sg/3Xcbx1X
@todayonlinesg
#trending: SIA flight attendant praised as 'angel' for helping passenger clean jeans using own stain remover pen
In a "friendly chat" with a cabin crew member she referred to as Aiden, Ms Paige Parker asked him "almost jokingly" if SIA had any stain removers, expecting the answer would be no.
✈️https://tdy.sg/3AxJC4T
@todayonlinesg
#trending: Is Amsterdam safer? S'porean woman's reasons for moving to the Netherlands spark debate online
Aside from her safety concerns, the weather was a major factor, as she found Singapore too hot and humid. "I can't be sweating perpetually," she wrote.
➡️https://tdy.sg/3Ti9EQf
@todayonlinesg
#trending: Japanese ramen shop ranks Singaporeans’ spice tolerance as ‘mid’; netizens agree
Out of 10 levels, Singapore and Malaysia are ranked in the middle while Indonesia is at the top with the highest spice tolerance.
➡️https://tdy.sg/4fNFrBQ
#trending: Influencer's praise of NDP crowd control leaves S'poreans grateful for reminder 'we are so blessed'
Ms Francesca Tanmizi, an Indonesian who lives in Singapore, told her 316,000 TikTok followers she was wowed by the efficiency of NDP crowd control, the speedy cleanup of rainwater and the friendliness of the personnel involved.
🇸🇬https://tdy.sg/3WByhIk
@todayonlinesg
#trending: New S'pore teen character in Marvel comic book sounds like burnt-out student, say netizens
A Redditor teased that the character's powers could be “the result of years of training by her kiasu Tiger mum under the Singapore academic system” rather than an actual superpower.
👩🎓https://tdy.sg/4dFadep
@todayonlinesg
#trending: Netizens praise Jetstar Asia's 20th anniversary song for celebrating uniquely Singaporean traits
One viewer wrote: "Please consider (Mr Van Der Ven) for NDP theme song. He writes his own music and can supply 20 different types of aunties."
➡️https://tdy.sg/3WqSn85