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

Резултати

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

Пребарај: #landscapes

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

@interesting_planet_facts · Post #452 · 28.07.2025 г., 22:22

🌎 Deep in southeastern Iran, the mysterious Kaluts desert features gigantic, wind-carved sand formations called “yardangs.” These natural sculptures stretch for kilometers, shaped by centuries of relentless wind erosion. ✨ #geology⚡#desert⚡#landscapes 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #591 · 19.08.2025 г., 20:22

🌎 Powerful enough to move mountains, glaciers shaped entire continents. As they advanced, their slow, grinding ice carved out valleys, lakes, and fjords still visible today. ✨ #geology⚡#glaciers⚡#landscapes 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #829 · 28.09.2025 г., 20:11

🌎 Southern China’s Stone Forest, or Shilin, is a dramatic landscape of towering limestone pillars shaped by both natural erosion and centuries of quarrying. Human mining over the last thousand years has altered parts of this ancient karst region, creating new rock formations and open spaces alongside original spires. ✨ #geology⚡#humanimpact⚡#landscapes 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #254 · 17.09.2025 г., 16:12

🌍 The Rice Terraces of Yuanyang in China were carved into steep mountains over centuries. These living heritage sites are so vast they create their own microclimate and reflect the region's cultural history. ✨ #heritage⚡#landscapes⚡#agriculture⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #50 · 15.08.2025 г., 00:12

🌍 The geographic shell of the Earth includes plateaus, plains, and mountain ranges, creating a patchwork that determines where rivers flow and where different climates form. ✨ #landforms⚡#climate⚡#landscapes⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Amazing Geography 🌍

@amazingeo · Post #690 · 14.04.2026 г., 20:31

🌍 In Japan, centuries-old forest areas called satoyama are shaped by human care for farming, wood, and water, blending wild nature and villages into landscapes rich in biodiversity and tradition. ✨ #interaction⚡#landscapes⚡#biodiversity⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #468 · 21.11.2025 г., 20:31

🌍 Some arid desert landscapes feature ancient, dried-up riverbeds called wadis that can flood suddenly after rare rains, quickly turning from bare channels to rushing streams in a matter of hours. ✨ #desert⚡#arid⚡#landscapes⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #385 · 17.10.2025 г., 20:31

🌍 In Indonesia, ancient forests and rice terraces share land with villages, blending wild and human-shaped environments. This mix supports rare wildlife while feeding local communities. ✨ #interaction⚡#landscapes⚡#sustainability⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #484 · 29.11.2025 г., 20:31

🌍 In China's southern hills, vast terraces transform mountains into rice fields. These hand-carved steps let farmers grow crops high above valleys, creating some of the world’s most scenic farmland. ✨ #agriculture⚡#landscapes⚡#rice⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #636 · 16.02.2026 г., 20:31

🌍 Italy’s Cinque Terre is a World Heritage Site where human-built terraced vineyards cling to steep cliffs beside the sea. Centuries of farming have shaped this landscape into a living cultural mosaic. ✨ #heritage⚡#landscapes⚡#vineyards⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #181 · 05.09.2025 г., 13:12

🌍 England’s Lake District is a UNESCO World Heritage Site where centuries of sheep farming shaped rolling hills and stone walls, blending natural scenery with a rich cultural landscape. ✨ #heritage⚡#landscapes⚡#UNESCO⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

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