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

Пребарај: #maqetuka

当前筛选 #maqetuka清除筛选

Farewell to Ambassador Mzuvukile Maqetuka 📅 March 31 marks the final day of the tenure of South African Ambassador to Russia and Belarus Mzuvukile Maqetuka. Today, he is departing from Russia. 💌 An excerpt from a farewell letter by the Honorary Consul of South Africa in Yekaterinburg, Sergey Mazurkevich, to Ambassador Maqetuka: "All our meetings have been truly memorable, and each time, you have emphasized the importance of fostering strong people-to-people ties. Your words have been a source of inspiration, guiding my efforts in this role. (...) Your Excellency, it has been an honor, privilege, and pleasure to know you personally and to serve as the Honorary Consul of South Africa under your leadership. My team and I remain committed to strengthening the ties between our nations, guided by the priorities you have set. Please accept our heartfelt gratitude, and our best wishes for your future endeavors." 🌍 Ambassador Maqetuka's dedication to building lasting connections and promoting cooperation between Russia and South Africa will be remembered and appreciated. Wishing him success in his future endeavors! #SouthAfrica#Russia#Diplomacy#Ambassador#InternationalRelations#Maqetuka#Mazurkevich

📚 At the international book festival Red Line, the Russian edition of Jim is Tired of Jo’burg by former South African Ambassador to Russia Mzuvukile Maqetuka was officially presented. 💬 In a lively dialogue, translator Dr. Dmitry Pobedash and editor Dr. Mikhail Brodsky explored the challenges of literary translation and shared fascinating stories about 🇿🇦 South Africa with the audience. 🤝 The event was made possible with the support of Ural Federal University Press and the Office of the Honorary Consul of South Africa in Yekaterinburg. #Culture#Literature#Festivals#SouthAfrica#Yekaterinburg#Translation#Maqetuka#Mazurkevich#UrFU

South Africa from A to Z: students, graduates, and professors of the Institute of International Relations (IIR) discovered many fascinating facts about the country! On March 22, South African English teacher Samora "Sam" Poswa held an engaging presentation at IIR, sharing insights about his homeland and answering numerous questions. The event was organized with the support of the Office of the Honorary Consul of South Africa in Yekaterinburg. The Office staff presented IIR Rector Dr. Irina Vylegzhanina with the Russian edition of Jim Is Tired of Jo’burg by South African Ambassador to Russia Mzuvukile Maqetuka, translated in 2024. They also spoke about the history of the project initiated by HC of South Africa Sergey Mazurkevich. #SouthAfrica#internationalrelations#education#culture#IIR#IMS#Maqetuka#Mazurkevich#Yekaterinburg

Во вторник 10 декабря Почётный консул Сергей Мазуркевич встретился в Москве с Послом ЮАР Мзувукиле Макетукой. Они обсудили текущие проекты офиса Почётного консула ЮАР и планы на 2025 год. #встречи#новости#Посол#Макетука#Мазуркевич _________________ On Tuesday, December 10, Honorary Consul Sergey Mazurkevich met with South African Ambassador Mzuvukile Maqetuka in Moscow. They discussed current projects of the Honorary Consul's office and plans for 2025. #meetings#news#Ambassador#Maqetuka#Mazurkevich

🇿🇦📖Jim may be tired of Jo’burg, but Yekaterinburg certainly isn’t tired of Jim! 📚 On August 22–24, the Red Line Book Festival (“Krasnaya Strokа”) — Yekaterinburg’s international book festival — will feature a new presentation of the Russian translation of Mzuvukile Maqetuka’s novel Jim Is Tired of Jo’burg. 📍The presentation format was discussed by representatives of the Office of the Honorary Consul of South Africa, translator Dr. Dmitry Pobedash (📸 right), and Dr. Aleksey Podchinyonov, the CEO of the Ural University Press (📸 left). 🗓 A year ago, an earlier presentation of translated chapters took place at the same festival: 🔗https://t.me/sarconsulurals/1340 📌 Details about the exact time and venue will be announced soon. #SouthAfrica#Yekaterinburg#Ural#RedLineFestival#Literature#AfricanLiterature#Translation#Maqetuka#UrFU#JimIsTiredOfJoburg