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

Пребарај: #vandalism

当前筛选 #vandalism清除筛选

🎙 Briefing by Russia's Foreign Ministry Spokeswoman Maria Zakharova (Moscow, November 7, 2025) 🔹Outcomes of Russia’s UNSC Presidency 🔹Kiev regime crimes 🔹Ukraine crisis 🔹Estonia’s introduction of a “fee for energy independence from Russia” 🔹Third advisory opinion of the UN International Court of Justice regarding Palestine 🔹Election of the new UNESCO Director-General during the 43rd session of the UNESCO General Conference 🔹The signing of a peace declaration by Cambodia and Thailand 🔹 2025 BRICS+ Counter-Terrorism Conference 📰Read 📺Watch #UN#UNGA On October 31, the Russian Federation completed its Presidency of the UN Security Council. During this period, the Council held a total of 22 meetings and 11 consultations. A broad range of conflict situations across nearly all regions of the world, as well as other pressing challenges to international peace and security, were considered. Russia’s Presidency reaffirmed our country’s strong authority as a founding member of the UN and a permanent member of its Security Council. The Russian Side made every effort to ensure the Council’s effective and result-oriented work. We will continue to work to ensure that the Council remains an effective tool for coordinating efforts to find collective responses to threats to international peace and security. #KievRegimeCrimes The Kiev neo-Nazi regime continues to attack civilian targets, terrorising the civilians in Russia. Over the past week, more than 70 Russian citizens suffered in artillery and drone strikes — 8 were killed and 63 injured, including 4 children. The brutal practice of deliberately targeting civilians by the Ukrainian neo-Nazis has been reported in all populated areas along the front line. #Estonia#Baltic#Vandalism Moscow is outraged by reports of yet another act of state vandalism in Estonia, this time against the memory of Soviet soldiers buried in the town of Loksa. In a profoundly disrespectful act, the remains of sailors from the destroyer Karl Marx and other Soviet soldiers who died fighting the Nazis between 1941 and 1945 have been exhumed using an excavator. Russia strongly condemns the immoral and criminal campaign being waged in Estonia to desecrate the remains of fallen anti-Nazi fighters. We reiterate that the destruction, damage, or desecration of war graves, even beyond Russia’s borders, is a criminal offence under the Criminal Code of the Russian Federation. #UNESCO On November 6 this year, the UNESCO General Conference, currently being held in Samarkand, elected the Organisation’s new Director-General – the renowned scholar and Egyptologist, former Egyptian Minister of Tourism and Antiquities, Khaled Ahmed El-Enany – for the term from 2025 to 2029. We welcome this decision. We are encouraged by the new Director-General’s pragmatic and constructive approach. #Cambodia#Thailand#ASEAN We welcome the signing of a joint declaration to settle the border conflict by Cambodia and Thailand at the ASEAN Summit in Kuala Lumpur on October 26. We remain confident that the arrangements arrived at with the assistance of Malaysia’s ASEAN Chairship will help overcome existing differences peacefully, establish a close bilateral dialogue, and ensure that the normalised situation will last long and remain durable. We believe many territorial disputes around the world are a legacy of Western colonial policy. Considering the worsening situation in the Asia-Pacific region, it is important to act in the spirit of unity and solidarity which is a hallmark of ASEAN.