Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Californian Gov. Gavin Newsom labeled JD Vance a “dips--t” in a string of stinging social media posts that included resurfacing images of the vice president in drag.
Vance spoke to reporters after a meeting with President Donald Trump and Democrats on Monday in an effort to avoid a government shutdown that could close services as early as Wednesday.
Little appeared to have been achieved, with both sides blaming the other before the midnight Tuesday deadline.
Newsom shared footage of the vice president from the White House Rapid Response X account pointing the finger at Democrats.
“You don’t put a gun to the American people’s head and say, ‘Unless you do exactly what Senate and House Democrats want you to do, we’re going to shut down your government,’” Vance told reporters outside the White House.
“That’s exactly what they’re proposing out there.”
#Vance#Newsom
👂More on Trump's Ear ⚠️
Academy Award-winning actress Halle Berry lashed out at California Gov. Gavin Newsom on Wednesday, arguing that he overlooks women and shouldn’t “be our next president.”
“At this stage in my life, I have zero f–ks left to give,” Berry said in remarks at the Dealbook Summit before taking aim at the Democratic governor, according to the Hollywood Reporter.
“Back in my great state of California, my very own governor, Gavin Newsom, has vetoed our menopause bill, not one, but two years in a row,” the “Catwoman” star continued. “But that’s OK, because he’s not going to be governor forever, and the way he has overlooked women, half the population, by devaluing us, he probably should not be our next president either. Just saying.”
#Newsom#Hollywood
👂More on Trump's Ear
Il presidente Donald #Trump rilancia su Truth un video generato con intelligenza artificiale che raffigura Barack #Obama e Michelle #Obama come gorilla e ripropone false accuse contro Dominion Voting Systems sulle elezioni 2020, suscitando condanne, tra cui quella dell'ufficio del governatore della California Gavin #Newsom: "comportamento disgustoso da parte del presidente. Ogni singolo repubblicano deve denunciarlo. Adesso".
@UltimoraPolitics24
Gavin Newsom naturally couldn’t resist trolling Donald Trump after the 79-year-old president posted an AI-generated video featuring him he shilling for magic “Medbeds.”
“Trump is about to shut down the government and rip health care from 20 million Americans. What’s he doing? Posting AI-generated slop about ‘miracle hospital beds’ that cure all illness,”
tweeted Newsom, 57.
“DONALD TRUMP HAS LOST IT,”
he added.
#Trump#Newsom#conspiracy
👂More on Trump's Ear ⚠️
Trump's signature will appear on dollar bills for the 250th anniversary of US independence 💵
The signature of US President Donald Trump will appear on new dollar bills that will begin to be printed in 2026. The decision is timed to coincide with the 250th anniversary of the adoption of the US Declaration of Independence, which will be celebrated on July 4, 2026. 🇺🇸
US Secretary of the Treasury Scott Bessent explained that there is no more visible way to celebrate the historical achievements of President Donald Trump than to place his name on dollar bills.
This will be a violation of a tradition that has been in place since the 19th century, when banknotes were traditionally signed by the Secretary of the Treasury and the Treasurer of the United States, rather than by the President. According to American media reports, the first $100 bills with Trump's signature may be printed as early as June.
"Now Americans will know exactly who to blame as they pay more for groceries, gas, rent, and healthcare," Democratic California Governor Gavin Newsom wrote on social media. ⚠️
#Trump#Bessent#Newsom
👂More on Trump's Ear ⚠️
👨👩👧👦📜SUPREME COURT BLOCKS CALIFORNIA FROM HIDING TRANS KIDS
🔹 Major Ruling: The Supreme Court has struck down California's controversial "Safety Act," which banned schools from forcing teachers to "out" trans kids to parents. 🛑🏳️⚧️
🔹 Parental Rights Win: Validating the concerns of conservative parents nationwide, the court affirmed that schools cannot keep secrets from families about a child's identity. 🏆👨👩👧👦
The battle for the classroom continues. For now, parental notification is the law of the land. California loses again. 🏛️
#SCOTUS#TransRights#ParentalRights#California#Education#Newsom
🏛️🇺🇸SCOTUS STRIKES DOWN CA "SAFETY ACT"
🔹 Supreme Court blocks California law that banned schools from "forced outing" of trans kids to parents 🏳️⚧️
🔹 Major victory for parental rights groups; huge blow to Gavin Newsom"s administration agenda 👨👩👧👦
🔹 Schools can now be required to notify parents if a child changes pronouns or identification 📝
🔹 "Parents have a fundamental right to know," say conservative advocates celebrating the ruling 🗣️
🔹 LGBTQ+ groups call it "shocking" and dangerous for vulnerable student populations ⚠️
California vs The Feds part 500. The culture war in schools just got a lot hotter. 🔥
#SCOTUS#California#TransRights#ParentalRights#Education#Newsom
Finally, we are free from the WHO. In this week's Throwback Thursday, we take a look back at the WHO and everything they've done for us in the name of "health."
https://drtenpenny.substack.com/p/tenpenny-throwback-thursday-4ae
#tenpenny#WHO#gavinnewsom#newsom#rfkjr#throwback
🔹👉🏻@SherriTenpenny
#USA#Senate
Il Governatore della #California Gavin #Newsom (#D|Centro-sinistra) ha nominato l'attivista politica Laphonza #Butler come nuova Senatrice, dopo la scomparsa di Dianne #Feinstein.
Laphonza Butler ha 44 anni, è afroamericana, lesbica e dal 2021 è presidente dell’organizzazione EMILY’s List, che si occupa di promuovere l’elezione di donne Democratiche al #Congress.
@OsservatorioEsteri