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

Резултати

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

Пребарај: #islands

当前筛选 #islands清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #477 · 01.08.2025 г., 00:22

🌎 The Falkland Islands are home to the only known population of the Cobb’s wren, a small brown bird found nowhere else on Earth. These birds thrive in predator-free habitats, showing how isolated islands can protect unique species from extinction. ✨ #biodiversity⚡#islands⚡#birds 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #706 · 07.09.2025 г., 18:22

🌎 Border oddities abound in Earth’s geography! The Diomede Islands, just 4 km apart in the Bering Strait, belong to different countries and are separated by the International Date Line, meaning they are 21 hours apart in time despite being visible from each other. ✨ #geography⚡#borders⚡#islands 👉subscribe Interesting Planet ​

Bali News

@balinews · Post #206 · 09.10.2024 г., 03:30

🚤Nusa Penida could be home to a floating hospital 🏥 Nusa Penida leaders are proposing a water ambulance service to respond quickly to emergencies. 🚨 There are currently no major hospitals on the islands of Nusa Penida, Nusa Lembongan and Nusa Ceningan near Bali. The small clinics that do exist are unable to treat emergencies and patients have to be brought to Bali by boat or evacuated by helicopter. @BaliNews #goodnews#health#islands

Amazing Geography 🌍

@amazingeo · Post #424 · 30.10.2025 г., 20:31

🌍 One of the youngest islands on Earth, Hunga Tonga-Hunga Haʻapai, formed in 2015 after an undersea volcanic eruption. New land like this is rare and offers scientists a natural laboratory. ✨ #islands⚡#volcanoes⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #465 · 30.07.2025 г., 03:22

🌎 The double coconut palm of Seychelles produces the world’s heaviest seed—up to 18 kilograms! Its giant, heart-shaped seed takes years to mature before dropping to the forest floor. ✨ #botany⚡#islands⚡#wonders 👉subscribe Interesting Planet

Amazing Geography 🌍

@amazingeo · Post #191 · 07.09.2025 г., 03:12

🌍 The Canadian Arctic Archipelago includes over 36,000 islands, making it one of the most complex island groups on Earth. These remote lands are mostly uninhabited and covered by ice much of the year. ✨ #islands⚡#arctic⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #463 · 19.11.2025 г., 12:31

🌍 Canada’s Manitoulin Island is the largest freshwater island in the world. It’s so big that it contains more than 100 lakes, and some of those lakes have islands of their own. ✨ #islands⚡#freshwater⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40702 · 26.02.2026 г., 00:20

The Philippines is an archipelago with about 7,641 islands. Around 2,000 islands are inhabited. More than 5,000 islands are unnamed. The islands are grouped into Luzon, Visayas, and Mindanao. The older count of 7,107 islands was updated after modern surveys. 🇵🇭🏝️🌊 [Read More] @googlefactss #Philippines#Islands#Geography#DidYouKnow#Facts

Amazing Geography 🌍

@amazingeo · Post #103 · 23.08.2025 г., 16:12

🌍 In recent decades, a growing number of small island nations are seeing rising sea levels drive migration, forcing some communities to relocate entirely from their ancestral homes. ✨ #migration⚡#islands⚡#climate⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #336 · 05.10.2025 г., 18:31

🌍 The ancient terraces of the Canary Islands blend natural volcanic slopes with centuries-old farming. These landscapes are so unique they’re recognized globally as a heritage site. ✨ #heritage⚡#agriculture⚡#islands⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #693 · 17.04.2026 г., 20:31

🌍 Indonesia is the world’s largest archipelago, made up of over 17,000 islands. Some, like Java, are densely populated, while others remain so remote they still hold undiscovered plant species. ✨ #archipelago⚡#islands⚡#biodiversity⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

ПретходнаСтраница 1 од 4Следна