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

Резултати

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

Пребарај: #extinction

当前筛选 #extinction清除筛选
Amazing Geography 🌍

@amazingeo · Post #461 · 18.11.2025 г., 12:31

🌍 Since 1970, vertebrate wildlife populations have dropped by an average of nearly 70% worldwide. Habitat loss and pollution are major drivers of this rapid, ongoing global decline. ✨ #environment⚡#extinction⚡#biodiversity⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1381 · 22.04.2026 г., 12:11

🌎 Layers of ancient mud and sand, called sedimentary strata, hold natural records of Earth’s history. These layers show changes in climate, ocean levels, and even mass extinction events over millions of years. The famous K-T boundary, found in rock layers worldwide, marks the asteroid impact that ended the age of dinosaurs about 66 million years ago. ✨ #geology⚡#fossils⚡#extinction 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #267 · 19.09.2025 г., 20:12

🌍 Nearly 90% of the world’s wetlands have disappeared since 1700, shrinking vital habitats and reducing natural flood protection for millions of people living downstream. ✨ #wetlands⚡#extinction⚡#flooding⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Interesting Planet 🌍

@interesting_planet_facts · Post #779 · 19.09.2025 г., 03:22

🌎 The Steller’s sea cow, a giant marine mammal, was discovered in the Bering Sea in 1741 and went extinct just 27 years later due to overhunting. This species reached lengths up to 9 meters and fed on kelp, leaving no close living relatives today. ✨ #extinction⚡#megafauna⚡#ocean 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1229 · 16.01.2026 г., 22:11

🌎 Around 252 million years ago, the Permian-Triassic extinction wiped out about 90% of marine species and 70% of land vertebrates. Massive volcanic eruptions in Siberia released greenhouse gases that drove rapid global warming, ocean acidification, and low oxygen levels—making it the largest extinction event in Earth's history. ✨ #extinction⚡#volcanoes⚡#paleoclimate 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #438 · 27.07.2025 г., 16:22

🌎 The Gomphothere, an ancient cousin of elephants, once roamed the Americas with shovel-shaped lower jaws. These extinct giants sported four tusks instead of two, thriving for millions of years before vanishing at the end of the last Ice Age. ✨ #paleontology⚡#megafauna⚡#extinction 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #1346 · 19.03.2026 г., 12:11

🌎 Strange bones found on the island of Malta belong to dwarf elephants and hippos that once lived there. These animals evolved smaller sizes due to limited island resources. The dwarf elephant species Palaeoloxodon falconeri stood just one meter tall at the shoulder. ✨ #extinction⚡#paleontology⚡#Mediterranean 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1209 · 10.01.2026 г., 12:11

🌎 The moa, a group of flightless birds native to New Zealand, stood up to 3.6 meters tall and weighed over 200 kilograms. DNA analysis reveals that moas’ closest relatives are the small, flying South American tinamous, not ostriches or emus as once believed. ✨ #moa⚡#extinction⚡#paleontology 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #843 · 01.10.2025 г., 18:11

🌎 The giant moa, once native to New Zealand, stood up to 3.6 meters tall and weighed about 230 kilograms. Moa vanished around 600 years ago, likely due to hunting by early Polynesian settlers. DNA studies show there were at least nine distinct moa species before extinction. ✨ #moa⚡#extinction⚡#paleontology 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #743 · 13.09.2025 г., 20:22

🌎 The dodo bird, once native to Mauritius, vanished by the late 17th century. Little was documented about its appearance or habits, leaving scientists puzzled. Recent studies of preserved bones and rare historical notes suggest the dodo was likely grayish with small wings and weighed up to 18 kilograms. ✨ #dodo⚡#extinction⚡#mysteries 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1269 · 02.02.2026 г., 22:11

🌎 In Siberia, the woolly mammoth roamed the tundra until about 4,000 years ago. Some frozen mammoth carcasses still contain preserved hair, skin, and even stomach contents. Recent DNA studies show mammoths were closely related to modern Asian elephants. ✨ #mammoth⚡#extinction⚡#Siberia 👉subscribe Interesting Planet 👉more Channels ​

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