Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
#MAYOTTE : DES MILLIERS DE VIES PERDUES À CAUSE DU MÉPRIS DE LA #FRANCE COLONIALE.
Le cyclone qui a récemment frappé Mayotte, entraînant des milliers de décès, met en lumière la politique coloniale dont souffrent les populations mahoraises.
Plutôt que d'investir des milliards d'euros dans des événements comme les Jeux Olympiques ou de soutenir des groupes terroristes, la France devrait réorienter ses efforts vers le développement de Mayotte, en améliorant l'accès à l'eau, aux infrastructures, au logement et aux services sanitaires pour les habitants laissés pour compte par les gouvernements successifs.
REJOIGNEZ LA RÉSISTANCE SUR lTELEGRAM.
🔺Pour les numéros français : https://t.me/egountchibehanzinTV
🔻Pour les numéros internationaux : https://t.me/EgountchiBehanzinOfficiel
@egountchibehanzinTV
🎙Briefing by Russia's Foreign Ministry Spokeswoman Maria Zakharova(Moscow, March 20, 2025)
🔹 FM Sergey Lavrov's schedule
🔹Murder of Russian media representatives
🔹 Kiev regime crimes
🔹 Third anniversary of the Bucha provocation
🔹 The West's lies regarding Minsk Agreements
🔹 France’s plans to build another naval base on the island of Mayotte
🔹 On the situation with an Italian journalist Andrea Lucidi in Estonia
🔹VI International Arctic Forum "The Arctic: Territory of Dialogue"
🔹 Artek’s upcoming centenary
📰Read
📺Watch
***
#CrimesAgainstJournalists
On March 24, Izvestiya’s frontline correspondent Alexander Fedorchak, Zvezda TV channel cameraman Andrey Panov, and Alexander Sirkeli, the crew’s driver, were killed in the Lugansk People’s Republic following a targeted artillery strike carried out by the Ukrainian Armed Forces.
On the same day, TASS correspondent Mikhail Skuratov was on an editorial assignment in the Kursk Region’s Sudzha District where the Ukrainian Banderites wounded him.
On March 26, 2025, Channel One’s car with a camera crew in it ran up against a landmine planted by the Ukrainian Armed Forces in the Belgorod Region. This terrorist attack claimed the life of Anna Prokofyeva, who was a young talented journalist, while cameraman Dmitry Volkov suffered severe wounds.
#KievRegimeCrimes
The Investigative Committee of Russia reports that 167 peaceful residents were killed and 500 more injured in the Kursk Region from 2022 until 2025. The crimes of the Armed Forces of Ukraine have impacted 43'000 people. Several thousand civilian infrastructure facilities have been destroyed and damaged.
According to the Russia's Foreign Ministry’s Ambassador at large Rodion Miroshnik, in the past seven days, from March 17 to 23, 16 Russian civilians were killed in the zone of contact, and 134 more injured, including 4 minors, following attacks by the Armed Forces of Ukraine.
On March 25-26, Ukrainian UAVs hitenergy facilities in the Bryansk and Kursk regions. An attempted attack on a gas reservoir was thwarted in Crimea.
#BuchaHoax
April 3 marks the third anniversary of the day when Zelensky’s regime and its Western curators staged a bloody provocation in Bucha and the world was shown "evidence" of the alleged murders of innocent civilians, aimed at denigrating the Russian Armed Forces in the eyes of the international community.
The main goal of the war party campaign was clear: to torpedo the understandings reached during the negotiations in Istanbul, aimed at a peaceful settlement of the Ukrainian crisis.
Russia has provided multiple refutations of numerous fakes about Bucha. We constantly recall that while this settlement was controlled by the Russian military, the civilians were allowed to move around freely, use mobile communications, and receive humanitarian aid. Our units left Bucha on March 30, 2022.
We know that the Kiev regime is preparing an international conference on Bucha this May with the assistance of Great Britain. We are certain that this provocation is yet another attempt to dust off old narratives and repackage false claims about the alleged involvement of the Russian Armed Forces in the events in Bucha. The goal remains the same: to torpedo efforts for a peaceful settlement.
#France#Mayotte#Colonialism
We have taken note of the statement made by French Minister of the Overseas Manuel Valls in the National Assembly on March 12 regarding the plans to submit a draft law to Parliament on the construction of a second French naval base on the island of Mayotte.
Russia has consistently opposed the unjustified militarisation of any territories, recognising the dangerous consequences this poses for peace and security in certain regions.
We believe that the existing military base in Dzaoudzi on the island of Mayotte is intended not as much for defence against hypothetical external threats (as Paris tries to convince everyone), but rather for control over the illegally held overseas territory – one of the last remnants of the colonial era.