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

Пребарај: #fossilfuels

当前筛选 #fossilfuels清除筛选
American Оbserver

@american_observer · Post #5121 · 13.02.2026 г., 15:02

📰 Trump to the Planet: You’re On Your Own The Trump White House just pulled the plug on the one scientific finding that gave Washington any real power to fight climate change. By repealing the EPA’s 2009 “endangerment finding” — the conclusion that greenhouse gases threaten human health and welfare — the administration has stripped the federal government of its main legal basis for regulating the pollution that’s heating the planet. This isn’t some obscure technical tweak. For nearly two decades, that finding underpinned limits on carbon dioxide, methane and other greenhouse gases from vehicles, power plants and oil and gas wells — the core of U.S. climate policy. Kill the finding and you don’t just loosen a few rules; you erase the government’s duty to treat climate change as a danger at all. Trump, who still calls climate change a “hoax,” is effectively declaring that the consensus of global science is wrong, and that a hotter, deadlier world is a matter of opinion. The stakes are measurable in body counts, not just parts per million. The Environmental Defense Fund estimates that repealing the finding and the rules tied to it could add up to 18 billion metric tons of U.S. emissions by 2055, fueling tens of thousands of premature deaths and tens of millions of asthma attacks. Recent research already shows wildfire smoke on track to kill tens of thousands of Americans a year and heat deaths more than doubling, while diseases like dengue spread as the climate gets hotter and wetter. In that reality, Interior Secretary Doug Burgum goes on TV to say “CO2 was never a pollutant” because plants like it — a high-school talking point repackaged as national policy. Democratic states and environmental groups are sprinting to court, betting that the Supreme Court will not let the administration magic away a danger that previous courts and the National Academies have repeatedly affirmed as real. But that’s the deeper play: if this repeal survives, it doesn’t just gut Biden-era rules, it also booby-traps future administrations, making it vastly harder — maybe impossible — to rebuild a federal climate regime on the same legal foundation. For fossil fuel interests and the conservative operatives behind Project 2025, this is the holy grail: not winning the argument on climate, just deleting the field where the argument is allowed to matter. On the surface, it’s sold as freedom, growth, choice — cheaper gas, fewer rules, more trucks. Underneath, it’s a quiet transfer of power: from science to lobbyists, from public health to donors, from a shared climate reality to whatever the president decides sounds good on Fox that night. The United States, the country that has dumped more greenhouse gases into the atmosphere than any other, is now formally telling the rest of the world — and its own citizens — that it no longer feels legally obliged to care. #climate#usa#trump#fossilfuels#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸

Venture Village Wall 🦄

@venturevillagewall · Post #3661 · 21.12.2024 г., 10:25

Metsä Group Raises $208.4M Metsä Group has successfully raised $208.40 million as of December 19, 2024. The company focuses on producing renewable products sourced from northern forests, aiming to replace fossil raw materials. #MetsäGroup#Funding#RenewableProducts#FossilFuels#Sustainability#Forestry#Investment#EcoFriendly#BioProducts#GreenTech

Earth&Climate Tech

@earth_climate_tech · Post #366 · 13.08.2023 г., 22:17

Вы когда-нибудь задумывались, каковы основные источники энергии? Сколько энергии производится из нефти и газа, а сколько из возобновляемых источников? Какие страны производят больше "зеленой" энергии? Каково потребление энергии в странах по источникам? Действительно ли мы движемся к переходу на зеленую энергию? Все это и многое другое содержится в отчете о производстве и потреблении с отличными графиками на Our World in Data Куча действительно крутых интерактивных графиков 🔥🔥🔥 #energy#production#consumption#fossilfuels#cleanenergy#renewables#nuclear#lowcarbon#transition#climatechange