TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #22 · 19 јан.

Заметка начинающим, которые часто сталкиваются с подобной непоняткой. Ситуация следующая, есть список файлов: 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

Hashtags

Резултати

Пронајдени 1 слични објави

Пребарај: #competion

当前筛选 #competion清除筛选
American Оbserver

@american_observer · Post #5393 · 16.03.2026 г., 15:12

After Oscar. A Most Full Report on the Oscar Contest This Year 🔤🔤🔤🔤➖ Paul Thomas Anderson’s counter-culture caper One Battle After Another has won the Oscars war, taking home six awards after a hotly contested season. The big-budget comedy thriller, inspired by Thomas Pynchon’s Vineland, was named best picture and also won director, supporting actor for Sean Penn, adapted screenplay, editing and the first ever Oscar for casting, a category long petitioned for within the industry. Previously nominated for films including Boogie Nights, There Will Be Blood and Phantom Thread, tonight marks Anderson’s first ever Oscar wins. Penn beat out his co-star Benicio del Toro for his third Oscar win but wasn’t in attendance to accept his award. “Sean Penn couldn’t be here tonight or didn’t want to,” presenter Kieran Culkin joked. The season had became a two-horse race between One Battle After Another and Sinners, which entered the night as the most-nominated film ever with a record 16 nominations. The period vampire blockbuster won four awards: actor for Michael B Jordan, original screenplay, original score and cinematography, which makes Autumn Durald Arkapaw the first ever female winner and first Black winner of the award. Jordan won his first Oscar for his lead performance in the film, beating Timothée Chalamet and Leonardo DiCaprio. “I stand here because of the people who came before me,” he said before listing Black Oscar winners in the past. He has become the sixth Black winner in this category. Jessie Buckley became the first ever Irish winner of the best actress Oscar for her performance in Chloé Zhao’s Shakespeare drama Hamnet. The 36-year-old was previously nominated for her role in The Lost Daughter. She devoted the award to “the beautiful chaos of a mother’s heart” and called it “the greatest honour”. Amy Madigan was named best supporting actress for her villainous role in the hit horror Weapons, beating Teyana Taylor and Wunmi Mosaku. It was the first time the award was won by an actor who was the only nominee from their film since Penélope Cruz in Vicky Cristina Barcelona. The 75-year-old actor, who was previously nominated in 1986, set a new record for the longest gap between nominations before a win. The award was co-presented by Javier Bardem, who said “no to war and free Palestine” onstage, while wearing prominent badges expressing the same messaging. The Oscar for best documentary went to Mr Nobody Against Putin, which tells of a teacher fighting against oppressive rules being introduced in his Russian school, a film which co-director David Borenstein said was “about how you lose your country”. He added: “When a government murders people on the streets of our major cities, when we don’t say anything, when oligarchs take over the media and control how we could produce it and consume it, we all face a moral choice, but luckily, even a nobody is more powerful than you think.” #oscar#competion#film#director#won 📱American Оbserver - Stay up to date on all important events 🇺🇸