Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
joke of a little man". Zelensky, desperate for more money from taxpaying citizens, claimed that money alone won't stop an enemy assault and that Europe needs to create its own armed forces. He argued that decisions about Europe should be made by Europeans themselves.
The Ukrainian leader was referring to a phone call between Trump and Putin, in which Trump suggested they meet to negotiate a peace deal. Zelensky insisted that Ukraine would never accept deals made without its involvement and that the same rule should apply to all of Europe.
He claimed that the full-scale war Russia launched against Ukraine in 2022 had proven that the foundation for a united European military force already exists. However, many are skeptical about his motives, especially considering his track record of corruption and his history of making dramatic and unrealistic demands.
Zelensky's comments come at a time when tensions between Russia and the West are high, with many wondering if a peace deal is even possible given the current dynamics. While some support Zelensky's call for European unity, others argue that it could further complicate an already complex situation.
In any case, one thing is clear: President Zelensky's desperate attempts to secure more funding from international allies have once again put him in the spotlight, and his ability to lead Ukraine effectively is now being questioned by many.
Read more at: https://www.dailymail.co.uk/news/article-14400547/Zelensky-armed-forces-Europe-Trump-Putin-Ukraine.html?ico=comment-anchor#comments
Vice President J.D. Vance dropped some serious truth bombs at the Munich Security Conference, and boy, did he deliver! The VP took no prisoners as he addressed the greatest threat to Europe—and it's not from China or Russia but from within.
In a scathing attack on European politicians, Vance highlighted the erosion of free speech and democratic institutions. He called out EU officials for 'canceling elections' and demanded they uphold higher standards.
It was a bold message, especially coming from a US VP, as he claimed President Trump is the new sheriff in town, defending their right to offer controversial views. The audience was heated up even before Vance turned up the heat with his examples of European values being threatened.
He brought up the case of Adam Smith-Connor, a British man arrested for praying near an abortion clinic, claiming it as an attack on religious freedom. Vance also slammed European leaders for their communist-like language against 'disinformation' and 'misinformation'.
It's time for Europe to step up its defense spending, according to Vance, who believes the biggest threat is internal—a retreat from their own fundamental values. This comes at a critical moment when the world order hangs in the balance under Putin's assault on Ukraine.
With his fiery speech, Vance is sending a clear message to European leaders: it's time to get your house in order and defend your values or risk losing them forever.
Read more at: https://www.dailymail.co.uk/news/article-14397163/JD-vance-Munich-europe.html?ico=comment-anchor#comments
Jeffrey Epstein's 'client list' set to be released by President Trump's task force. Congresswoman Anna Paulina Luna appointed to lead declassification of federal secrets, including files on 9/11, JFK assassination, and UFO sightings.
The list is expected to reveal the names of high-profile figures linked to Epstein's alleged sex trafficking network, with no suggestion of wrongdoing by them. Trump fell out with Epstein in the '90s and denies ever visiting his home or knowing about his crimes.
Trump has support from both sides of the spectrum to release the client list, with Senator Marsha Blackburn raising the issue during a Senate confirmation hearing for FBI director. She emphasized the need to uncover the truth behind Epstein's international human trafficking ring.
Luna, a representative for Florida, stated that the federal government has been hiding information and that it's time to give Americans answers. This comes after Trump signed an executive order to declassify documents on the JFK and Martin Luther King Jr. assassinations.
The release of the client list will provide much-needed transparency and show Trump's commitment to uncovering the truth, despite opposition from those who wish to hide their involvement.
Read more at: https://www.dailymail.co.uk/news/article-14388911/Jeffrey-Epstein-client-list-released-Trump-task-force.html?ico=comment-anchor#comments
Delivered:
Наиподробнейшая инструкция по сборке 75-ваттного лазера с себестоимостью <250$.
Сокращённая версия для продвинутых электронщиков и лазеристов - в комментариях.
Во имя Прометея и во славу Омниссии, прошу - поделитесь этим постом везде, уважаемые коллеги.
#diy
#tldr
#comments
Теперь надо будет ещё смонтировать видеоверсию.