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

Пребарај: #russiankremlin

当前筛选 #russiankremlin清除筛选
Russian Consulate in Cape Town

@rusconct · Post #1969 · 07.11.2024 г., 21:18

📺 Vladimir Putin addressed the plenary session of the 21st annual meeting of the Valdai International Discussion Club 🌍We are destined to live in an era of fundamental, even revolutionary changes, and not only to comprehend but also to take a direct part in the most complex processes of the first quarter of the 21st century. We are witnessing the formation of a completely new world order, nothing like we had in the past. 💪🏻New powers are rising. Nations are becoming more and more aware of their interests, their value, uniqueness and identity, and are increasingly insistent on pursuing the goals of development and justice. 📌Societies are confronted with a multitude of new challenges, from exciting technological changes to catastrophic natural disasters, from outrageous social division to massive migration waves and acute economic crises. ⚠️Experts talk about the threat of new regional conflicts, global epidemics, about complex and controversial ethical aspects of interaction between humans and artificial intelligence, about how traditions and progress reconcile with each other. ❌Western liberalism has expressed itself in extreme intolerance and aggression towards any alternative, towards any sovereign and independent thought, and today supports neo-Nazism, terrorism, racism and even mass genocide of civilians. 💣International conflicts may result in mutual destruction. Weapons capable of doing this exist and are constantly being improved as technology develops. And the number of owners of such weapons is expanding, and no one guarantees that in case of final destruction of legal and moral norms it will not be involved. ❌The West's calls to inflict a strategic defeat on Russia, the country with the largest arsenal of nuclear weapons, demonstrate the extreme adventurism of Western politicians. Such a blind belief can turn into a world tragedy. We have come to a dangerous line. 🇷🇺Unlike our opponents, Russia does not perceive Western civilization as an enemy, does not ask the question "us or them". 🙌🏻 Common efforts could be directed with much greater benefit, a return on solving truly common problems that affect everyone: from the problems of demography and social inequality to climate change, food security, medicine and new technologies. Full version: Valdai Discussion Club meeting #RussianKremlin#RussianMFA#VladimirPutin