Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🚨Переломный момент 🚨
Сегодня – Международный день чистой энергии. Знали ли вы, что
Великобритания достигла более 50% возобновляемой электроэнергии в течение
ЧЕТЫРЕХ кварталов подряд!
Еще впечатляющее: 58% электроэнергии Британии
поступило из чистых источников в 2024 году, а последняя угольная электростанция
навсегда закрылась в сентябре.
🌎Будущее – за возобновляемой энергией! 🌎
#CleanEnergy#SustainableFuture
Everyone deserves the right to nutritious, affordable, and sustainable food.
On #WorldFoodDay, let's commit to working towards a world where everyone has access to the food they need for a healthy and fulfilling life.
#HealthyLiving
#FoodSecurity#SustainableFuture
January 28 — International Reducing CO₂ Emissions Day
📸👩🏫👨🏫Every action counts! Today is a reminder that students are not just learners, but future leaders of a more sustainable world.
✔️From saving energy and choosing public transport to supporting green innovations, small daily choices can make a big difference for our planet.
🔼Let’s work together for cleaner air, a healthier environment, and a greener future. The change starts with us.
#GreenUniversity#ClimateAction#CO2Reduction#SustainableFuture
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
🌟 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
Green University Students Join Tashkent “Young Ecologists” Council
🎓Council members:
🟢Deputy Chair: Baxtiyorova Saodatxon
🟢Manager of Ecological Innovation, Startups and Grants: Danayeva Farzona-bonu
🦉This membership gives our students the opportunity to actively participate in ecological initiatives, innovations and the development of a green economy.
#YoungEcologists#GreenUniversity#Ecology#Innovation#SustainableFuture
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
🏔️International Mountain Day
🗓Today, we celebrate International Mountain Day — a reminder of the incredible role mountains play in our lives. They provide fresh water, protect unique ecosystems, and inspire millions around the world.
🌱Let’s raise awareness, appreciate nature, and work together to preserve these powerful landscapes for future generations.
#InternationalMountainDay#SustainableFuture#GreenUniversity#YouthForNature#EcoAwareness
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
📣 Eco Club JMCU — tabiat uchun birlashgan yangi oila! Har bir uchrashuv — yashil kelajak sari qo‘yilgan bir qadam.🌿
💬💬💬
📣 Eco Club JMCU — a new family united for nature! Each meeting is a step toward a greener future.🌿
💬💬💬
📣 Eco Club JMCU — новая семья, объединённая ради природы! Каждая встреча — шаг к зелёному будущему.🌿
#EcoClubJMCU#GreenFamily#SustainableFuture#GoGreen#EcoLife#NatureMatters
🕊Telegram |📱Instagram
☀️ “Ziyo Forum” yoshlar markazida BMT kuni munosabati bilan “Youth United for the UN Day: Empowering Sustainable Future” sessiyasi bo‘lib o‘tdi!
🇺🇳27-oktabr kuni “Ziyo Forum” yoshlar markazida yoshlar uchun ilhomlantiruvchi sessiya tashkil etildi. Tadbir davomida Alisher Asrorov— UNODC Youth Network Leader in Uzbekistan, Webster Universitetining Career & Business Development menejeri va sobiq BMT Yoshlar Kengashi raisi — BMTning O‘zbekistondagi faoliyati, Barqaror Rivojlanish Maqsadlari (SDGs) hamda yoshlarning global tashabbuslardagi o‘rni haqida o‘z tajribasi asosida so‘zlab berdi.
📌Ishtirokchilar ochiq muloqotda faol qatnashib, “Kahoot” viktorinasida o‘z bilimlarini sinovdan o‘tkazishdi. Tadbir yakunida eng faol yoshlarga maxsus sovg‘alar topshirildi va umumiy suratga tushildi.
🌍Sessiya iliq va ilhomlantiruvchi muhitda o‘tib, yoshlarni global fikrlash va barqaror kelajak sari ilhomlantirdi.
📸 Barcha suratlarni quyidagi havola orqali ko‘rishingiz mumkin:
👉https://disk.yandex.ru/d/1A8GU1Uc6bujhg
☀️ “Youth United for the UN Day: Empowering Sustainable Future” session was successfully held at Ziyo Forum Youth Center!
🇺🇳On October 27, a special and inspiring session took place at the Ziyo Forum Youth Center. Alisher Asrorov— UNODC Youth Network Leader in Uzbekistan, Career & Business Development Manager at Webster University, and former Chair of the UN Youth Advisory Board — shared his insights on the UN’s role in Uzbekistan, the Sustainable Development Goals (SDGs), and the importance of youth participation in global initiatives.
📌Participants actively engaged in open discussions and tested their knowledge through the interactive Kahoot quiz. The most active attendees received special gifts, and the event concluded with a group photo.
🌍The session took place in a warm and inspiring atmosphere, motivating young people to think globally and contribute to a sustainable future.
📸 Check out all the event photos at the link below:
👉https://disk.yandex.ru/d/1A8GU1Uc6bujhg
#ZiyoForum#UNDay#YouthEmpowerment#SustainableFuture#UNUzbekistan#SDGs#YouthCenter
#ClimateCrisis
🌍 The world is sinking into fossil fuels
Oil, gas, and coal account for 75% of global greenhouse gas emissions and nearly 90% of CO₂ emissions.
🔥 2024 became the hottest year in recorded history — global temperatures have risen 1.5°C above pre-industrial levels for the first time (according to @CopernicusClimate).
❄️ Consequences:
• Melting of polar ice caps
• Rising sea levels
• Intensifying storms and droughts
• Populations who contributed least to climate change are suffering the most
⛽️ Despite the crisis, consumption of oil, gas, and coal is increasing.
🌡 According to @UNEP, 2024 set a record for CO₂ emissions.
Many governments and corporations are promising “net zero,” yet in practice, fossil fuel extraction is being doubled.
🗣 “Governments are doubling fossil fuel extraction — this is double the risk for humanity and the planet,”
— said UN Secretary-General António Guterres.
📊 According to the @InfluenceMap report:
Just 57 corporations and state-owned companies were responsible for 80% of CO₂ emissions from fossil fuel and cement production between 2016 and 2022.
💡 The solution is a transition to clean energy and local resources.
But without transparency, investigative journalism, and public pressure, change will not happen.
🟢 Climate responsibility is not an abstract concept. It involves real names and real actions.
#EcoUz#ClimateCrisis#Copernicus#UNEP#CleanEnergy#ZeroEmission#StopFossilFuel#AralRegion#SustainableFuture
☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.