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

Пребарај: #newtgingrich

当前筛选 #newtgingrich清除筛选
Newt Gingrich

@newtgingrich · Post #4714 · 23.05.2023 г., 13:45

#newtgingrich : RT @AmerNewMajProj: Just 1 in 5 Americans agree with Biden and the Democrats that slowing the rate of spending increases is an irresponsible cut. https://t.co/Z6QdnPa5iW

Newt Gingrich

@newtgingrich · Post #4713 · 23.05.2023 г., 08:44

#newtgingrich : RT @SpeakerMcCarthy: President Biden and I just had a productive meeting in our negotiation to responsibly raise the debt limit. It should have happened months ago, but there is a path for him to avoid defaulting on the debt. https://t.co/u3rDJmrl7v

Newt Gingrich

@newtgingrich · Post #4710 · 22.05.2023 г., 18:46

#newtgingrich : The American people see strong leadership from Speaker Kevin McCarthy, and the latest polls have his favorability as the highest among Congressional leadership. https://t.co/nv7UcCb3Tc

Newt Gingrich

@newtgingrich · Post #4709 · 22.05.2023 г., 17:44

#newtgingrich : RT @GOP: .@SpeakerMcCarthy: “The Democrats since they took the majority have been addicted to spending and that’s going to stop. We’re going to spend less than we spent last year.” https://t.co/cqu1xLLsWA

Newt Gingrich

@newtgingrich · Post #4708 · 22.05.2023 г., 17:44

#newtgingrich : RT @CallyGingrich: Human trafficking survivors recently testified before members of the U.S. House of Representatives about the need for lawmakers to pass legislation to increase resources for survivors and expand efforts to hold perpetrators accountable. https://t.co/MedJ3mILN0https://t.co/oeqSNDl86E

Newt Gingrich

@newtgingrich · Post #4706 · 21.05.2023 г., 22:43

#newtgingrich : RT @SpeakerMcCarthy: I literally asked the president: "What is the number? How much debt must America have before you say, 'let's stop borrowing from China?'" https://t.co/nAd1wMtDOw

Newt Gingrich

@newtgingrich · Post #4705 · 21.05.2023 г., 21:43

#newtgingrich : RT @SpeakerMcCarthy: Just got off the phone with the president while he’s out of the country. My position has not changed. Washington cannot continue to spend money we do not have at the expense of children and grandchildren. Tomorrow, he and I will meet in person to continue negotiations.

Newt Gingrich

@newtgingrich · Post #4704 · 21.05.2023 г., 17:43

#newtgingrich : The University of Austin, TX, is taking a new innovative approach to improving the American education model. Interesting reading. @AcademicRenewal https://t.co/I1dEFJnKuq

Newt Gingrich

@newtgingrich · Post #4702 · 21.05.2023 г., 13:43

#newtgingrich : We are a lot closer to the Biden default with the President’s game playing and arrogance. House Republicans will NEVER support a Biden tax increase. Biden’s comments in Japan were dishonest and destructive. If we default it will be Biden who forced it.

Newt Gingrich

@newtgingrich · Post #4701 · 21.05.2023 г., 13:43

#newtgingrich : Speaker McCarthy and House Republicans have a tremendous opportunity to create a better American future. @amspectator https://t.co/ibQaV07PsC

123•••5•••10•••15•••20•••25•••30•••35•••40•••45•••50•••55•••60•••65•••70•••75•••80•••8384
ПретходнаСтраница 1 од 84Следна