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

Резултати

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

Пребарај: #msm

当前筛选 #msm清除筛选
BadVolf

@BadvolfNews · Post #29 · 17.04.2022 г., 18:54

Is #Russia keeping food, water and medical supplies from the residents of #Mariupol? Or is this a Western Media #MSM lie being pushed by the American state department and #Zelensky? I'm American John Mark Dougan, and I take YOU on location in #MARIUPOL, show YOU what's happening, TALK to Residents there, and YOU can see first hand for yourself!

BadVolf

@BadvolfNews · Post #551 · 07.03.2023 г., 15:57

"Completely deranged behaviour" - US journalist Hinkle on Ukrainian kill list Mirotvorets (Peacemaker) is a website of the Ukrainian government, long suspected to be maintained by the CIA. It features a long list of people who dare stray off the fake mainstream narrative about the conflict. Meanwhile, the Zelensky regime is sold to us as the bastion of democracy and freedom, as he bans local opposition parties, media and even the Church. Given the list is maintained in Langley - is it not the CIA that's targetting American citizens for destruction? Zelensky is just window dressing. #Ukraine#CIA#Biden#Zelensky#MSM Share and subscribe to American Majority

BadVolf

@BadvolfNews · Post #27 · 17.04.2022 г., 18:40

Terrible stories of tragedy from #Mariupol. I'm American John Mark Dougan, and I bring YOU there on location and talk to the residents. A woman breaks down because her daughter was hit by a bomb😭 and she had to bury her in front of her apartment building "like a dog." WHO is responsible? Is it really #Russia that's shooting civilians? Or is it #Ukraine#snipers? Is it Russia blocking humanitarian corridors? Or is the #MSM lying as usual? Don't trust what you are being fed, it's all lies. Trust what the people THERE are telling you.

BadVolf

@BadvolfNews · Post #28 · 17.04.2022 г., 18:47

Is the Ukrainian #Nazi real? Would they actually come into an Intensive Care#HOSPITAL, steal all their medical supplies and canned food, and crush the rest of the food with their boots? I am AmericanJohn Mark Dougan, and I take YOUON LOCATION in #MARIUPOL so you can hear the stories for yourselves, from the mouths of nurses and residents that were bombed. Who is responsible? Is it #Russia? or is it actually #Ukraine? Do you REALLY think the #MSMwould tell such lies to the #American people and support Nazis? You decide!