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

Резултати

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

Пребарај: #communalresistanceseries

当前筛选 #communalresistanceseries清除筛选
Venezuelanalysis

@venanalysis · Post #1579 · 24.05.2024 г., 16:20

The Pancha Vásquez Commune in Apure State, Venezuela, focuses on cattle rearing and agriculture. Despite private land ownership limiting their capacity, they’ve established a Collection and Distribution Center to aid local producers. Discover how communards in the Venezuelan plains region [Llanos] produce, organize, and resist the impact of the US blockade. Click here to read the full interview 👉🏼shorturl.at/qfmo6 #communalresistanceseries

Venezuelanalysis

@venanalysis · Post #1589 · 31.05.2024 г., 20:54

Llaneros Resist the Blockade! Facing severe impacts from the US blockade, the Pancha Vásquez Commune has innovated with communal exchanges and local production shifts, such as using buffalo for dairy due to higher yield. The new Collection and Distribution Center aims to reduce intermediary dependency and stabilize food prices. Click here to read the full interview 👉🏼shorturl.at/T9XD6 #communalresistanceseries#sanctions

Venezuelanalysis

@venanalysis · Post #1632 · 05.07.2024 г., 19:56

The Coporo Indígena community in Apure, Venezuela, maintains its traditions and communal land practices despite violence and the US blockade. Recently, they welcomed 18 families displaced by violence, showing the strength of their communal ties. 'In Pumé society, we all work together and share the little that we have: shelter, water, and other goods, while the care of the community and the land is everybody’s task,' said Gladys García, spokesperson for the Coporo Indígena Communal Council. Read more in the full interview, part of the communal resistance series, here 👉🏼shorturl.at/uLjEo #communalresistanceseries#indigenouspeoples

Venezuelanalysis

@venanalysis · Post #1593 · 07.06.2024 г., 17:35

The Pancha Vásquez commune in Apure State, Venezuela, consisting of fourteen communal councils, embodies the region's deep-rooted traditions in agriculture and cattle rearing. It's also where Hugo Chávez sharpened his political vision from 1985-1988, intertwining his socialist ideals with the local folklore. From the legendary “El Silbón” to “La Sayona,” the tales Chávez encountered in Elorza have become a vital part of the area's folklore, reflecting the enduring impact of his legacy. Read the full interview here 👉🏼shorturl.at/jaxwE #communalresistanceseries#communes#HugoChavez

Venezuelanalysis

@venanalysis · Post #1786 · 25.10.2024 г., 19:00

Amazonian Huo̧ttö̧ja̧ People and the Bolivarian Process The Río Cataniapo Commune showcases the strength of Indigenous organizations in the Venezuelan Amazon, with approximately 1,500 participants committed to communal living and traditional agriculture. 'Our way of living is far more communitarian than the sabari way of life,' notes Irene Pérez, of the 5 de Julio-Las Pavas Communal Council, is an artisan and campesina, emphasizing their commitment to ensuring no one goes hungry. Read the full interview here: https://venezuelanalysis.com/general/amazonian-huo%cc%a7tto%cc%a7ja%cc%a7-people-and-the-bolivarian-process-rio-cataniapo-commune-part-ii/ #VAInterview#communalresistanceseries#communes#indigenouspeoples

Venezuelanalysis

@venanalysis · Post #1802 · 08.11.2024 г., 21:22

In the Río Cataniapo Commune, communal power and tradition intersect to sustain food sovereignty and resist the impacts of the US blockade. The commune produces its staple casabe from yuca, managing every step from harvest to market. Read the full interview here 👉🏼https://shorturl.at/WRgF9 #VAInterview#communalresistanceseries#communes#indigenouspeoples#communalandworkingclassresistance

Venezuelanalysis

@venanalysis · Post #1779 · 18.10.2024 г., 21:44

‘The Commune Is Nothing New Here’: The Rio Cataniapo Commune The Rio Cataniapo Commune, located in the Venezuelan Amazon, brings together 1,500 people, mainly Indigenous, to protect the Cataniapo River and develop a sustainable agricultural economy. As Enrique Martínez, a Huo̧ttö̧ja̧ leader, explains: ‘Self-government and collective ownership are part of our heritage.’ Indigenous leadership remains key, but the community also seeks modern improvements while preserving tradition. Read the full interview here 👉🏼https://shorturl.at/Xgst1 #VAInterview#communalresistanceseries#communes#indigenouspeoples#communalandworkingclassresistance

Venezuelanalysis

@venanalysis · Post #1649 · 12.07.2024 г., 14:25

In the Venezuelan plains region, a multi-generational group of women works to build Bolivarian socialism amid the US blockade. Nacidos para Vencer con Chávez [Born to Triumph with Chávez] is a women-led commune in a rural context with a long history of patriarchal oppression. This fledgling commune seized upon Chávez’s idea as a way forward in difficult times, attempting to build community and increase production, while connecting with other communes through the Communard Union. Read the full interview as part of the VA Communal Resistance Series 👉🏼shorturl.at/r06V5 #communalresistanceseries#communes#communalresistance#workingclassresistance