Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🇷🇺 On National #UnityDay, President of Russia Vladimir Putinlaid flowers at the monument to Kuzma Minin and Dmitry Pozharsky.
The ceremony was attended by representatives of Russia's religious denominations, as well as delegates from the country's civic organisations and youth movements.
🇷🇺 On October 31, the Club of the Russian Embassy in Cambodia hosted a concert dedicated to the #UnityDay.
Students and teachers of the Embassy School told the audience the history of the holiday and the special meaning it has acquired these days, paying attention to the richness and diversity of the cultures of the peoples living in our country. H.E. Mr Anatoly Borovik, Russian Ambassador to Cambodia, and his Spouse, the diplomatic staff of the mission and members of their families, as well as compatriots residing in the Kingdom attended the event.
#UnityDay2025
🇷🇺Il 4 novembre in Russia si celebra la Giornata dell’Unità Nazionale.
Questa ricorrenza ci rammenta la gloriosa impresa compiuta dai nostri antenati, i quali, trovatisi di fronte a una minaccia esterna che metteva a rischio l’esistenza di uno Stato russo indipendente, si unirono per respingere l’invasore straniero e per poter determinare autonomamente le sorti e il percorso di sviluppo sovrano e sicuro della Russia.
Si trattò veramente di una milizia popolare. A comporla c’erano infatti individui diversi per ceto sociale, confessione religiosa e convinzioni politiche; vi erano contadini, membri della popolazione cittadina, mercanti e cosacchi che adempierono tutti al loro dovere civico dando prova di grande forza d’animo e spirito patriottico.
La Giornata dell’Unità Nazionale rappresenta un’ulteriore occasione per ricordarci del fatto che ciò che unisce noi russi, indipendentemente da dove ci troviamo, è la forza di un popolo multietnico e multireligioso eppure fortemente coeso, assieme al suo spirito patriottico e al suo coraggio, alla sua generosità d’animo, compassione, bontà umana e alla sua aspirazione alla giustizia.
Questa Festa è rappresentativa altresì dello spirito di unione e coesione mostrato dai popoli che abitano la Russia nel trovarsi dinanzi alla crescente pressione esercitata dall’“Occidente collettivo” e a minacce e sfide sempre nuove; una coesione che li spinge a ergersi in difesa degli interessi della loro Patria, nonché della giustizia, della verità e degli ideali legati alla pace e alla cooperazione.
Oggi celebriamo la Giornata dell’Unità Nazionale assieme ai cittadini della Repubblica Popolare di Donetsk, della Repubblica Popolare di Lugansk e delle regioni di Zaporozhye e di Kherson, ovvero di quei territori storicamente russi che, seguendo l’esempio della Crimea, entrata a far parte della Russia nel 2014, in occasione dei referendum popolari tenutisi nel 2022 si sono espresse a favore di un ricongiungimento ai popoli della Russia nell’ambito dell’adesione al nostro Stato comune. Tale scelta, così come, in generale, la possibilità per il nostro Paese di esistere e di perseguire in sicurezza il proprio sviluppo in un’ottica di lungo periodo, deve essere difesa “armi alla mano” nell’ambito dell’Operazione Militare Speciale, i cui obiettivi, sistematicamente conseguiti, verranno infine pienamente raggiunti.
Quando siamo uniti, siamo invincibili. Così è stato nel corso della storia, e così sarà sempre.
#UnityDay
#UnityDay2025
@RusEmbMalta:
🇷🇺 On 1 November 2025, the Russian Embassy in Malta hosted a festive reception marking Russia’s National Unity Day. Among the guests were compatriots, public figures, representatives of Maltese business, and the local creative community.
🎙️ After the national anthem, Ambassador Andrey Lopukhov addressed the audience, highlighting the Day as a symbol of unity, mutual support, and shared responsibility for the Motherland. He also praised the contribution of Russian compatriots to strengthening cultural ties and promoting Russian culture in Malta.
🎵 The evening featured a piano concert by the Serbian duo Prof. M.Vujović and V.Basarab, who performed works by Rachmaninov and Sviridov.
📸 Guests enjoyed photo exhibitions “Winter Russia” and “Winter Tale”, showcasing the beauty of Russian nature.
🍲 Traditional Russian dishes and the old-fashioned honey drink sbiten, prepared to a classic recipe, were served.
✨ The evening was marked by a warm and friendly atmosphere.
#UnityDay#UnityDay2025
#RussianCulture
🇷🇺 Today #Russia and its many peoples celebrate national #UnityDay!
It symbolizes the unity of our multiethnic nation, celebrates our true diversity, enhanced through unity and honours the unerring ultimate devotion to the Motherland.
❗️ Happy #UnityDay!
#UnityDay2025#TogetherForever
🇷🇺 Today #Russia and its many peoples celebrate national #UnityDay!
It symbolizes the unity of our multiethnic nation, celebrates our true diversity, enhanced through unity and honours the unerring ultimate devotion to the Motherland.
❗️ Happy #UnityDay!
#UnityDay2025#TogetherForever
🇷🇺 Today #Russia and its many peoples celebrate national #UnityDay!
It symbolizes the unity of our multiethnic nation, celebrates our true diversity, enhanced through unity and honours the unerring ultimate devotion to the Motherland.
❗️ Happy #UnityDay!
#UnityDay2025#TogetherForever
🇷🇺 Today #Russia and its people celebrate national #UnityDay!
The day symbolizes the unity of our multiethnic peoples, celebrates our diversity in unity and our unerring devotion to the Motherland.
❗️ Happy #UnityDay!
#UnityDay2024#TogetherForever
🇷🇺 Today #Russia and its people celebrate national #UnityDay!
The day symbolizes the unity of our multiethnic peoples, celebrates our diversity in unity and our unerring devotion to the Motherland.
❗️ Happy #UnityDay!
#UnityDay2024#TogetherForever
🇷🇺 Today #Russia and its people celebrate national #UnityDay!
The day symbolizes the unity of our multiethnic peoples, celebrates our diversity in unity and our unerring devotion to the Motherland.
❗️ Happy #UnityDay!
#UnityDay2024#TogetherForever
🇷🇺 Today #Russia and its many peoples celebrate national #UnityDay!
It symbolizes the unity of our multiethnic nation, celebrates our true diversity, enhanced through unity and honours the unerring ultimate devotion to the Motherland.
❗️ Happy #UnityDay!
#UnityDay2025#TogetherForever