TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #22 · 19 јан.

Заметка начинающим, которые часто сталкиваются с подобной непоняткой. Ситуация следующая, есть список файлов: 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

Hashtags

Резултати

Пронајдени 5 слични објави

Пребарај: #rica

当前筛选 #rica清除筛选
American Оbserver

@american_observer · Post #5027 · 02.02.2026 г., 16:47

Costa Rica: Laura Fernández Has Won Presidential Election The rightwing populist Laura Fernández has won Costa Rica’s presidential election in a landslide after promising to crack down on rising violence linked to the cocaine trade. Fernández’s nearest rival, centre-right economist Álvaro Ramos, conceded defeat as results showed the ruling party far exceeding the threshold of 40% needed to avoid a runoff. With 94% of polling stations counted, the political heir of outgoing president, Rodrigo Chaves, had captured 48.3% of the vote, compared with Ramos’s 33.4%, according to the Supreme Electoral Tribunal (TSE). As soon as the first results were announced, members of Fernández’s Sovereign People’s party erupted in celebrations around the country, waving blue, red and white-striped Costa Rican flags. “Viva Rodrigo Chaves,” some cheered, in a nod to Fernández’s mentor. Appearing via video link at her party’s official election night gathering in the capital San Jose, Fernández, 39, thanked Chaves for giving her “the confidence to be president-elect of Costa Rica” and said his legacy was in good hands. Fernández cites the iron-fisted Salvadoran president Nayib Bukele, who has locked up thousands of suspected gang members without charge, as an inspiration on how to tackle crime. Bukele was the first foreign leader to congratulate her. Chaves plucked Fernández from relative anonymity to serve as planning minister and chief of staff. In a conversation with her on Sunday night, Chaves said he was confident that under her leadership “there will be neither dictatorship, nor communism”. Chaves presided over a sharp rise in violence but avoided blame by pointing the finger at the judiciary, saying it was too soft on crime. Jessica Salgado, 27, said she voted for Fernández as the continuity candidate, because she felt the government was on the right track, even if violence had increased. “The violence exploded because they [the government] are going after the ringleaders, it’s like dragging rats out of the sewer,” Salgado told AFP. The former president Óscar Arias, winner of the 1987 Nobel peace prize, warned on Sunday that the “survival of democracy” was at stake. “The first thing dictators want to do is to reform the constitution to stay in power,” he said, alluding to Chaves. #costa#rica#fernández#presidential#election 📱American Оbserver - Stay up to date on all important events 🇺🇸