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

Пребарај: #bricsoutreach

当前筛选 #bricsoutreach清除筛选

🇷🇺🇲🇳 President of Russia Vladimir Putin and President of Mongolia Ukhnaagiin Khurelsukh held a meeting in Ulaanbaatar. 💬President Putin: First of all, I want to thank you for the invitation. It has, in fact, become a good tradition for us to meet in Mongolia every five years to mark the remarkable highly significant events in our shared history. You have listed the dates we will be commemorating this year. Each of these dates holds special significance for both Russia and Mongolia. I would like to add that Erdenet, which you have mentioned, was planned by architects from Leningrad. I am also pleased to note that the Russian-Mongolian relations have been developing on a new foundation. Our countries have experienced growth in trade, despite the various challenges we have faced, including those you have mentioned, such as COVID. In fact, relations between our countries are progressing well across all areas. Apart from the economy and politics, where we continue to cooperate quite actively, I would like to highlight the successful collaboration in culture and education. The Intergovernmental Commission has been working proactively and there are good results. During our discussions today, we will undoubtedly touch upon the key trends in our economic collaboration. To conclude my opening remarks, I would like to extend an invitation for you to visit Kazan, Russia, where the #BRICS Summit will be held later this year. This will be the first top-level event following the recent expansion of the association. I hope you will take part in the #BRICSOutreach – #BRICSplus format. We look forward to seeing you in Russia. International consultations began with a conversation between the two Leaders in a restricted format, followed by a meeting with the participation of the two countries’ delegations. ✍️ A set of documents was signed following talks. The Government of the Russian Federation and the Government of Mongolia signed agreements on the development of basic project documentation for the reconstruction of the TPP-3 thermal power plant in Ulaanbaatar, as well as on cooperation in the supply of oil products and on providing Mongolia with aviation fuel. The Russian Federal Service for the Oversight of Consumer Protection and Welfare and the Ministry of Health of Mongolia signed an Agreement on cooperation to ensure epidemiological welfare with regard to plague. In addition, the Russian Federation Ministry of Natural Resources and Environment and the Ministry of Environment and Climate Change of Mongolia signed a Memorandum of Understanding on cooperation in the conservation of Lake Baikal and the Selenga River. Presidents Vladimir Putin and Ukhnaagiin Khurelsukh also made statements to the media. #RussiaMongolia