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

Резултати

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

Пребарај: #cleanpower

当前筛选 #cleanpower清除筛选
Rosatom Global

@rosatom_global · Post #123 · 20.08.2025 г., 10:26

🌟 Celebrating 80 Years of the Russian Nuclear Industry! 🌟 Today marks a historic milestone — the 80th anniversary of the Russian nuclear industry. It’s not just a story of technology and science, but of vision, resilience, and the determination to transform challenges into opportunities for the future. ⚛️ Breakthroughs that redefined possibility The Russian nuclear industry became a leader in the peaceful use of atomic energy. The world's first nuclear power plant in Obninsk was launched, created the first nuclear icebreaker and tokamak. 🚀 Rosatom today Today, the State Corporation "Rosatom" creates advanced technologies for a wide range of industries: today the state corporation not only builds nuclear power plants, providing clean energy to the country and the world, but also creates new materials — super-strong, environmentally friendly, helps develop the Arctic and the Northern Sea Route, develops nuclear medicine methods to defeat incurable diseases, advances quantum technologies to solve global human problems. 👨‍👩‍👧‍👦 A dream for the future Today, the nuclear industry has a big new dream — a long and healthy life for people through clean atomic energy, advanced nuclear medicine methods, new materials, and modern digital technologies. 🌍 We dream of a world where energy is limitless, life is healthier, and humanity thrives. And together, we will make this dream a reality. We are proud & happy! ✨ #NuclearEnergy#CleanPower#Innovation#SustainableFuture

Venture Village Wall 🦄

@venturevillagewall · Post #3646 · 21.12.2024 г., 10:24

Accelergen Energy Raises $20M Accelergen Energy has secured $20 million in funding as of December 19, 2024. The firm focuses on delivering clean power assets characterized by robust and sustainable locational value through strategic investments, development, commercialization, and optimized operations. For more details, visit Accelergen Energy. #Accelergen#Energy#Funding#CleanPower#Investment#Sustainability#RenewableEnergy#Development#Commercialization#Operations#ClimateTech#GreenEnergy#Ecosystem#Infrastructure#PowerAssets#Technology#StrategicInvestment#CleanTech#EcoFriendly#LocationalValue