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 слични објави

Пребарај: #incompetence

当前筛选 #incompetence清除筛选
BadVolf

@BadvolfNews · Post #833 · 11.09.2023 г., 15:14

🚨 BREAKING NEWS 🚨 🔴 Biden's Vietnam Press Conference Cut Short 🔴 In a shocking display of incompetence, the Biden administration once again revealed their true colors during President Joe Biden's press conference in Vietnam. As Biden stumbled through his answers, White House staff abruptly ended the event, cutting his microphone and playing jazz music to drown out his ramblings. While attempting to address stability and global access to change, Biden was interrupted by his press secretary, Karine Jean-Pierre, who hastily declared an end to the conference. Astonishingly, Biden continued speaking, unaware that his mic had been muted. The bizarre scene escalated further as jazz music filled the room, leaving the 80-year-old president confused and still attempting to respond to questions. As the music grew louder, Biden reluctantly retreated from the stage, whispering and shuffling behind a black curtain. Throughout the 26-minute engagement, he even used the infamous phrase, "lying dog-faced pony soldier," contributing to his already questionable credibility. This incident comes after Biden's whirlwind trip, where he attended the G20 Leaders' Summit in India before hastily jetting off to Vietnam. Instead of displaying strength and leadership, Biden's performance only highlighted his lack of stamina and clarity. His joke about not knowing if it was morning or night further emphasizes the worrying state of his mental acuity. To make matters worse, Biden shared a convoluted story from a John Wayne movie that had little relevance to the pressing issues at hand. It seems that Biden's administration is more focused on theatrics than addressing the concerns of the American people. This latest debacle only adds to the mounting evidence that Biden is nothing more than a puppet of America's deep state, lacking the competence and independence to lead our nation effectively. The American people deserve better than this. #BidenAdministration#Incompetence#DeepStatePuppet