Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🇷🇺Russia’s Foreign Ministry Ambassador-at-Large for the G20, APEC and BEP issues Marat Berdyev:
Russia’s participation in key multilateral forums such as the #G20 and #APEC contributes to the accelerated formation of a multipolar world order and economic system.
📈In terms of aggregate GDP, the BRICS members have already surpassed the G7, with their share standing at 37%, compared to less than 30% for the G7.
According to some expert estimates, the countries of the Global Majority will drive up to 75% of global economic growth over the next few decades.
Russia plays a significant role in this positive trend of fair optimization of production potentials.
🤝We continue to actively develop international economic cooperation, focusing on friendly regions.
According to the Federal Customs Service (FCS), Russia's external trade volume in 2024 is expected to reach $700 billion.
Approximately 70% of export-import operations already involve the Asia-Pacific Region (#APR).
🌍Trade with Africa has been expanding, reaching a peak of $25 billion in 2023.
The Russian economy grew by about 4% in 2024, demonstrating resilient performance.
This growth occurred against the backdrop of more modest global averages, limited to 3.1%, and stagnation in many European countries.
🌾Russian companies are playing an increasingly significant role not only in supplying critical energy and food resources but also in high-tech sectors and manufacturing industries.
We are intensifying transactions in national currencies, particularly the Russian ruble, which accounts for 80-90% of trade with key partners such as China and the EAEU.
Under the initiative of President Vladimir Putin, the Big Eurasian Partnership (#BEP) is building a transit framework centered on Russian territory.
Transit capacity is expanding, and the utilization of the "West-East" and "North-South" transport corridors is increasing, along with the operation of the Northern Sea Route (#NSR).
🚢In the past year, the NSR handled a record volume of over 37 million tons of commercial cargo.
At the #G20 and #APEC significant momentum has been given to the reform of global economic institutions in the interests of the Global South/East.
📈Constructive approaches have been adopted, aiming to preserve an open trade and investment environment, form energy balances on a technologically neutral basis, and support digital transformation.
❗️We will continue to move forward with partners in this promising direction at multilateral economic diplomacy platforms.
Photo: www.rosstip.ru
#G20#APEC#RussianMFA
Împreună cu colegii din Blocul Patriotic am prezentat astăzi platforma noastră electorală, cu care participăm la aceste alegeri parlamentare.
Inițiativele noastre sunt orientate spre: păstrarea suveranității, neutralității și identității moldovenești; crearea unei punți între Est și Vest; construirea unui stat de drept, unde fiecărui cetățean să i se garanteze protecția și echitatea socială; reunificarea țării; suveranitate economică; un stat în interesul poporului, nu al funcționarilor.
Noi credem în Moldova! Pe 28 septembrie votați pentru Blocul Electoral Patriotic al Socialiștilor, Comuniștilor, Inima și Viitorul Moldovei!
::::::::::::::
Вместе с коллегами по Патриотическому блоку сегодня представили нашу предвыборную платформу, с которой мы участвуем в этих парламентских выборах.
Наши инициативы направлены на: сохранение суверенитета, нейтралитета и молдавской идентичности; создание моста между Востоком и Западом; построение правового государства, где каждому жителю будут гарантированы социальная справедливость и защита; объединение страны; экономический суверенитет; государство в интересах народа, а не чиновников.
Мы верим в Молдову! 28 сентября голосуйте за Патриотический избирательный блок социалистов, коммунистов, сердца и будущего Молдовы!
#BloculPatriotic#Moldova#BEP#CredemÎnMoldova#ВеримВМолдову
Мы победим – это понимают даже «жёлтые». Но мы должны будем и отстоять нашу победу.
Призываю всех быть готовыми выйти 29 сентября на защиту нашей общей победы. Мы обязаны сделать это ради наших детей и внуков, ради Молдовы!
#BEP#ПатриотическийБлок#CredemÎnMoldova#ВеримВМолдову#Moldova#BloculPatriotic