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

Резултати

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

Пребарај: #uluwatu

当前筛选 #uluwatu清除筛选
Bali News

@balinews · Post #457 · 08.07.2025 г., 09:55

🏚Demolition of illegal buildings has begun in Bingin 📰 Protests have been unsuccessful. Mass demolition of illegal buildings has begun on Bingin Beach: more than forty warungs, boutique hotels, and surf schools are to be dismantled. 📍 The authorities call it the restoration of state land, while local entrepreneurs fear losing their only source of income. Among the establishments that are to disappear from the coastal map are the varungs Didi's, Kelly's, and Ombak. #beaches#Uluwatu#realestate@BaliNews

Bali News

@balinews · Post #132 · 02.08.2024 г., 10:01

🏄‍♀️Rip Curl Cup kicked off in Uluwatu 📍 One of the most prestigious competitions in world surfing has started at the Balinese spot Padang Padang. 🌊 On which of the days in August the awards will be drawn, no one knows. Organizers, judges and athletes will be waiting for the best waves, the so-called "pipes", to show all that they know how to do for a month. 🏆 This year the format of the Rip Curl Cup has been updated. The organizers decided to follow the ideas of gender equality and agreed to hold separate competitions for women at the same time with men. The last time this happened in Bali was 21 years ago. President of Rip Curl Indonesia James Hendy explained that the decision to create a women's division this year was made after the success of Canadian surfer Erin Brooks, who competed with men at the last Rip Curl Cup last year and reached the final, in which at first even led. 🖥 You can watch the broadcast of the championship itself, as well as find out the date of the championship at the link. 🎉 The main party of Rip Curl Cup-2024 will start at 17:00 on August 30 and will continue until midnight. @BaliNews #events#beaches#beaches#sports#Uluwatu

Bali News

@balinews · Post #120 · 19.07.2024 г., 11:02

🛣Details about the construction of a district road in Bukit District authorities are set to solve the road issue in Uluwatu by laying a new district road. Construction of the first section from Siligita village to Sawangan in Nusa Dua district has already started. The original idea was to extend the toll road, which now runs from the airport to Nusa Dua, all the way to Uluwatu. Right now, traffic on the main road jl. Uluwatu is difficult because it is both a hub of commerce and the main thoroughfare of the area, used by everyone from locals to construction vehicles and tour buses. The land acquisition budget for 2024 will be $16 million, with the next one already promised to increase to $19 million. According to an insider in Bali's land office, all consideration of new housing development in the green zone on Bukit is now halted just in time for the land acquisition for the new roads. @BaliNews #roads#roads#authorities#Bukit#Uluwatu#NusaDua