Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
#2006 – 25 FEB 2006
We Never Start a Premature Revolution
"..like Albert Pike said, the Grand Master of Freemasonry, the High Pope of Masonry, he said, "we never begin a premature #revolution. We always, always prepare the groundwork before we even begin the launch of the revolution itself." | Transcript
👇 LISTEN:
PODCAST
#2009 – 17 DEC 2007
Revolution shaping social Evolution
The Fisher Kings (professors) casts a net, not for fish, but for select individuals, the select Revolutionary Vanguard, who bring forth Revolution, a type of propoganda, indoctronation.
Alan Watt Blurb: "It’s beautiful when you help to CREATE a state of misery and poverty in nations, get it ripe for #revolution, put out the propaganda and bring forth men who speak on behalf of YOU, who always vocalize what you’d like to vocalize if you could find the words. That’s why they always get an intelligentsia well versed in speechmaking to guide the people, who always end up generally worse off than they were before. That’s the TECHNIQUE that’s used upon peoples." Transcript
👇 LISTEN:
PODCAST
On January 22, 1905, in St. Petersburg, Russia, peaceful protesters led by Father Gapon marched to the Winter Palace to ask the Tsar for better working conditions and rights. The soldiers opened fire on the crowd, killing and wounding many people. This event, called Bloody Sunday, started unrest that led to the 1905 Russian Revolution.
🩸🇷🇺
[Read more]
@googlefactss#BloodySunday#Russia #1905 #History#Revolution
In the cities of Iran today, during the celebration of the anniversary of the Islamic Revolution, the flags of the United States and Israel were actively burned.
#iran#celebration#anniversary#revolution
📱American Оbserver - Stay up to date on all important events
🇺🇸
Ximena González Broquen, a social scientist leading a center at Venezuela’s prestigious Institute for Scientific Research (IVIC) and compiler of several essay collections, discusses the Ethics of Liberation as a framework that challenges the top-down, market-driven logic of conventional scientific research institutes in the latest VA interview. She advocates for a more democratic research environment while aiming to build bridges with organized communities.
Read the full interview here 👉🏼https://shorturl.at/PHqTf
#VAInterview#Revolution#science#interview
📰 The Holy Succession Show: Tehran Edition
Iran’s clerics are prepping to crown a new Supreme Leader — while the capital burns like a refinery-themed apocalypse. Tehran’s skies turned orange overnight, fuel depots exploded, and the fire’s glow was bright enough for the mullahs to read their succession notes without electricity.
“With the fire it felt like night became day, and then with all the smoke, the day turned back into night,” said a Tehran resident.
The official line? Israel hit “military fuel sites.” The unofficial one? Iran’s oil empire just got a free light show courtesy of U.S. taxpayers. Washington pretends it’s all about stability, Jerusalem calls it self-defense, and everyone else just watches oil prices rise like a holy sacrament.
Ayatollah Khamenei is dead, his son Mojtaba is allegedly next in line — proving again that in God’s republic, power is hereditary. The clerics want to project calm, but their version of “stability” looks like orange skies, falling drones, and desalination plants exploding in Bahrain.
Trump, meanwhile, plays wartime CEO from Air Force One. On Monday, he was “all in” on Kurdish allies. By Saturday, he’d downsized that policy — too “complex,” he said. Management pivot. Same bombs, different press release.
Iran vows revenge. Israel promises “many more targets.” And the U.S. keeps striking Revolutionary Guard sites while denying the obvious: no war “for democracy” ever ends before the markets are satisfied.
The Middle East right now isn’t a battlefield — it’s a burning stage set for yet another script about God, oil, and power families. Everyone acts loyal, everyone dies on camera, and the credits always roll in dollars.
#iran#israel#us#war#oil#regimechange#oligarchy#revolution
📱American Оbserver - Stay up to date on all important events
🇺🇸
When discussing historic speeches, one stands out: President Hugo Chávez at the UN General Assembly on September 20, 2006.
He labeled U.S. President George W. Bush a war criminal and highlighted Western hypocrisy regarding democracy and peace—right from “the devil’s house.”
Chávez criticized the UN for its alignment with U.S. interests and called for reform led by the Global South. He underscored the ongoing struggle for change and the potential for a better future.
Click here to learn more and watch the key quotes 👉🏼https://shorturl.at/guOJh
#Milestone#HugoChávez#UN#Revolution
BDX Revolution
Sauvignon Blanc
Франция 🇫🇷, Бордо AOC, белое, сухое, крепость 12%, моносорт Совблан.
Качественно, без изысков, вкусно, отлично на каждый день.
В бокале солома и лёгкая зелень.
В носу характерные ароматы - зелёное яблоко, желтый грейпфрут и абрикосы, цветочные ноты с мягким дрожжевым оттенком, нотки лайма.
Вкус без яркости, но свежий, гладкий, с хорошей кислотностью.
Ценник +/- 900р. Но, попадается в сетях с хорошей скидкой до 600р.
Чин! 🍷
#BDX#Revolution#наКаждыйДень
#Sauvignon_Blanc#Bordeaux
@pro_Wines