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 слични објави

Пребарај: #ethiopianhighlands

当前筛选 #ethiopianhighlands清除筛选

🏗️ **ETHIOPIA: THE NEW INVESTMENT HOTSPOT** 🏗️ **ETHIOPIA: THE NEW INVEST 💰 Ethiopia's highlands are becoming Africa's new luxury destination! International investors and wealthy individuals are building exclusive estates in the mountains. 🏔️d wealthy individuals are • Foreign billionaires building private compounds at 2,500m+ elevation • Perfect climate year-round (15-25°C) • Stunning mountain views and clean air • Privacy and security in remote highlands 🌍e building exclusive es• Chinese companies: $13+ billion in infrastructure • Turkish investors: Industrial parks and textiles • Gulf states: Agriculture and real estate • European investors: Renewable energy projects 🏭 building exclusive estates in • Grand Ethiopian Renaissance Dam (GERD) • Addis Ababa Light Rail expansion • New industrial cities and economic zones • Luxury mountain resorts and eco-lodges 📈estors and wealthy • Fastest-growing economy in Africa (pre-2020) • Strategic location connecting Africa, Middle East, Asia • Young, educated workforce • Government incentives for foreign investment 🌟 From ancient highlands to modern investment paradise! ከጥንታዊ ተራሮች ወደ ዘመናዊ የኢንቨስትመንት ገነት! 🇪🇹 #Ethiopia#ኢትዮጵያ#Investment#LuxuryRealEstate#EthiopianHighlands#Development

## 🏔️ ETHIOPIAN HIGHLANDS VS SWISS ALPS: THE MOUNTAIN SHOWDOWN ## 🏔️ የኢትዮጵያ ተራሮች VS የስዊስ አልፕስ ⛰️ Time to settle this once and for all! --- ## 🇨🇭 SWISS ALPS PROS: Pretty postcards, chocolate, fancy resorts CONS: ❌ $300+/night hotels ❌ $8 coffee ❌ Overrun with tourists ❌ Zero human history --- ## 🇪🇹 ETHIOPIAN HIGHLANDS PROS: ✅ Where humanity learned to WALK! ✅ Gelada monkeys, Ethiopian wolves ✅ UNESCO Simien Mountains ✅ $20-50/night hotels ✅ $1 coffee ceremony ✅ Cliff monasteries ✅ 3.2 million years of history *ከሰው ልጅ መነሻ ተራሮች!* --- ## 📊 HEAD-TO-HEAD HISTORY: Cheese vs HUMAN EVOLUTION ✅ WILDLIFE: Cows vs Geladas & wolves ✅ HOTEL: $300 vs $20 ✅ COFFEE: $8 vs $1 ✅ CROWDS: Packed vs Undiscovered ✅ SCORE: Ethiopia 9 - Switzerland 2🏆 --- ## 💰 VACATION COST (1 week) SWISS ALPS: $3,356 💸 ETHIOPIAN HIGHLANDS: $557 🎉 SAVINGS: $2,799 (buy a car!) --- ## 🤔 THE VERDICT SWISS ALPS: "Look at our expensive hotels!" ETHIOPIAN HIGHLANDS: "We invented WALKING." 🚶‍♂️ --- ## 🏆 WINNER: ETHIOPIAN HIGHLANDS! 🇪🇹 Why? ✅ Witnessed human evolution ✅ 20x cheaper ✅ Unique wildlife ✅ Less crowded ✅ REAL coffee ✅ Marathon legends train here ✅ Gelada monkeys > cows *Switzerland is cool. Ethiopia is LEGENDARY.* 🔥 --- VISIT SIMIEN MOUNTAINS!🇪🇹⛰️ *Why be a tourist when you can be an EXPLORER?* ✨ #SimienMountains#EthiopianHighlands#SwissAlps#VisitEthiopia#BudgetTravel#UNESCO#EthiopianPride

## ⛰️ THE ROOF OF AFRICA: WHERE EARTH TOUCHES HEAVEN ## ⛰️ የአፈሪካ ጋራ: ምድር ሰማይ የሚመሰከርበት 🌍 КОГДА ГОРЫ КАСАЮТСЯ НЕБЕС! Simien Mountains — Ethiopia's crown jewel and UNESCO World Heritage site where ancient volcanic peaks pierce the clouds at 4,500 meters! ⛰️ 🌅 THE DRAMATIC LANDSCAPE: These jagged ridges were sculpted by millions of years of volcanic fury, creating one of Earth's most breathtaking panoramas. *Эти зубчатые вершины — самый драматичный пейзаж на планете!* *እነዚህ የተበዳደሩ አጫያዎች በዓለም ውስጥ የተሳከሩ ምብጣት ምክንያቶች ነው!* Deep gorges plunge 1,500 meters below — called "the chess pieces of the gods" by locals for their dramatic, sharp pinnacles. 🐒 UNIQUE WILDLIFE: Home to the endangered Gelada baboons — the "bleeding heart" monkeys found NOWHERE else on Earth! *Самые редкие павианы в мире живут только здесь!* *በዓለም አንደ ቦታ የሚገኙ የጋላዳ ብድንዎች እዚህ ብቻ ይገኛሉ!* These gentle giants graze the highland meadows in massive troops, living peacefully at altitudes that would leave most humans breathless. 🌟 KUINDZHI'S VISION BROUGHT TO LIFE: At sunset, these mountains transform into layers of gold and shadow — like stepping into a painting by the Russian master Arkhip Kuindzhi. Light becomes sculpture, air becomes canvas, and the soul expands infinitely. *На закате горы превращаются в живую картину Куинджи!* *በሰሙን መግረብ ጋታ አያቶች የኩይንዅጂ እሳት ይሆናሉ!* This is Ethiopia. Where nature paints with light and shadows, where time stands still, and where every breath feels sacred. 📸Swipe through: Photo 1-2: Real dramatic vistas → Photo 3: Algorithmic art in Kuindzhi style! *Фото 1-2: Реальные панорамы → Фото 3: Алгоритмическое искусство!* #SimienMountains#የሲሚኤንአያቶች#Ethiopia#ኢትዮጵያ#UNESCO#Kuindzhi#AlgorithmicArt#የአልገሪዝምእሳት#EthiopianHighlands#የኢትዮጵያአያቶች#MountainMagic 🇪🇹@ethiopia