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

Пребарај: #mgimo81

当前筛选 #mgimo81清除筛选

🌐 Today marks the 81st anniversary of the founding of the Moscow State Institute of International Relations!Congratulations to all – alumni, students, professors, and friends of the university – on the birthday of their beloved alma mater! 📜Historical background: 81 years ago, on October 14, 1944, the People’s Commissariat for Foreign Affairs of the USSR, headed by Vyacheslav Molotov, decided to establish a specialized educational institution for diplomatic training. In the final years of the Great Patriotic War, it became clear that the Soviet Union needed a new generation of professionals for its foreign service. The growing number of international contacts and negotiations on the post-war world order required highly qualified experts fluent in foreign languages, as well as in history, law, and economics. Such specialists were also needed for work in international organizations that were being planned after the war – above all, the United Nations and its affiliated bodies. 🌍In 1946, #MGIMO opened its doors to foreign students, laying the foundation for its international academic reputation. Since then, it has become one of Russia’s most international universities: today, students from more than 90 countries study here, and foreigners make up about 16% of the total student community. In 2025 alone, 400 students from 55 countries enrolled in the freshmen year. Last year, Russia’s leading university specializing in international relations celebrated its 80th Anniversary – 👉#Recap. Over the decades of its active and fruitful work, MGIMO has rightfully earned its reputation as a world-class university – a genuine “foundry” of diplomats, journalists, and even presidents. 💬President of the Russian Federation Vladimir Putin: MGIMO has firmly established itself among the world’s leading centers for the training of international specialists. For many decades, its graduates have formed the professional “backbone” of Russia’s diplomatic service. Genuine professionalism also distinguishes MGIMO alumni working in other areas – in government agencies, academia, education, business, and the media. It is no coincidence that a MGIMO diploma is highly valued not only in Russia, but also abroad. 💬Foreign Minister of the Russian Federation Sergey Lavrov (MGIMO, Class of 1972): Diplomacy is the art of negotiation. The formation of a multipolar world is a long process that may take an entire historical era. MGIMO graduates will definitely have enough work to do. ✊We wish #MGIMO enduring prosperity, inspiration, and countless new triumphs! May the university always remain a place where the spirit of knowledge, friendship, and aspiration reigns – where every new generation of students feels pride in their alma mater, finds support, loyal friends, and their true calling! #MGIMO81