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

Пребарај: #alternativeviewpoint

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

@rusconct · Post #1765 · 01.08.2024 г., 16:56

LESSONS OF HISTORY REPEATED ✍️Article by Ambassador of Russia to South Africa Ilya Rogachev (31 July 2024) READ IN FULL Key points: 🔹 Obsessed with the idea to inflict a military defeat upon Russia and split it into several smaller states with limited sovereignty, the collective West is heading towards a war against Russia, and decisions of the latest NATO summit in Washington D.C. corroborate that. "Europe is preparing for war. The pro-war train has no brakes, and the driver has gone mad” - Hungary’s Premier V.Orban". 🔹There is a very common opinion in Russia that approximately once in a centenary, the West braces up and comes to the Russian soil with a sword, where it gets beaten up and retires with its nose bloodied to remain calm for another 100 years. 🔹The Time of Troubles in Russia (XVII century) was accompanied by foreign military interventions (Poland, Sweden) which endangered the very existence of Russia as a sovereign state. But in 1612 people’s militia ousted the invaders. 🔹The XVIII century saw yet another major clash with Europeans known as the Great Northern War. During Swedish King Charles XII’s Russian campaign, in 1709, the army of invaders was completely decimated by Russian troops under the command of Peter the Great. 🔹In about 100 years, a new attempt to clamp Russia was made as Napoleon Bonaparte of France in 1812 led his ‘Grand Army’ into the ill-fated invasion. 600,000 soldiers of his army came to Russia in June 1812, and in only 6 months their remnants were chased away by Field Marshal Kutuzov’s troops. In 1814, the Russian army entered Paris. 🔹The XX century saw another large-scale invasion of Russia from the West. Our country survived World War I accompanied by inner political turmoil with three revolutions, the Civil War and foreign military interventions involving UK, France, USA etc. ☝️ Only two decades later Nazi Germany attacked the USSR. Hitler intended to conquer the USSR by the end of 1941, but it didn’t turn out the way he expected. On 30 April 1945, as the Red Army was storming Berlin, he committed suicide in the basement of the Reich Chancellery. 👉 Russian historian V.Klyuchevsky once wrote that history does not teach any lessons but punishes one for not learning them. The West should stop rewriting history and start learning it, in order to prevent history from repeating itself every 100 years. #alternativeviewpoint#embassyofrussia#rogachev#russia#southafrica