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

Резултати

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

Пребарај: #russiaday2023

当前筛选 #russiaday2023清除筛选

🇷🇺 On June 10, 2023, a state reception on the occasion of the national holiday - #RussiaDay was held at the Russian Embassy in Malta. Among the guests were compatriots, public figures, entrepreneurs, representatives of education, science and culture. ❗️Russian Ambassador to Malta H.E. Andrey Lopukhov addressed the audience with a welcoming speech, emphasizing the importance of this annual event for the consolidation of the Russian community living in Malta. He also noted that Russia is ready to cooperate with those countries that declare their readiness and willingness to cooperate with us. 📷The photo exhibitions "Achievements of Russia" and "Beauty of Russia" were presented to the audience. 🎵The evening was accompanied by live performances of Russian and Maltese musical compositions. The guests were offered dishes of the traditional Russian cuisine. The reception was held in a warm and friendly atmosphere. #RussiaDay2023🇷🇺🇷🇺🇷🇺

Russian Mission to ASEAN

@aseanrussia · Post #482 · 17.06.2023 г., 15:37

🇷🇺 On June 15, 2023, the state reception on the occasion of #RussiaDay was held at the Hotel Mulia Senayan in Jakarta. The celebration was attended by esteemed representatives of the Indonesian government, socio-political, business, academic, creative and religious circles, compatriots, journalists, as well as foreign diplomats. 🎙️Welcoming remarks at the function were delivered by H.E. Mrs Lyudmila Vorobyeva, Ambassador of the Russian Federation to the Republic of Indonesia (read in full), H.E. Mr Evgeny Zagaynov, Ambassador of the Russian Federation to ASEAN, and H.E. Mr Budi Gunadi Sadikin, Minister of Health of the Republic of Indonesia, as the Guest of Honour. 💬Ambassador Lyudmila Vorobieva: It is a pleasure to welcome you all at the reception on the occasion of the Day of Russia. We are celebrating the unity and the strength of our country which is one of the main players on the global arena and whose people is looking into the future with confidence and pride. Russia and Indonesia have a long history of successful cooperation traditionally based on principles of friendship, mutual understanding and trustworthy dialogue. 🎵 The cultural programme of the event included works of great Russian composers P.I.Tchaikovsky and S.V.Rachmaninov played by graduates of Russian musical universities, as well as pieces by local dance ensembles and musicians. The Indonesian song "Rayuan Pulau Kelapa" performed in two languages — Russian and Indonesian — took a special place in the programme of the evening. 📸 The Embassy also organised an art exhibition of Russian landscapes which allowed guests to experience the authentic character of our Motherland and to enjoy picturesque views from various parts of Russia. #RussiaDay #RussiaDay2023

Russian Mission to ASEAN

@aseanrussia · Post #473 · 12.06.2023 г., 03:49

🇷🇺 On June 12, we celebrate #RussiaDay across the entire country and abroad. It reflects #Russia’s contemporary development, as well as its centuries-old path, endeavours & achievements. 🇷🇺 Happy Russia Day! #RussiaDay#RussiaDay2023#Russia1Love#WeAreRussia