Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
LinkedIn’da topilgan maslahat:
Professional o’sishni tezlashtirish va atrofdagilardan farq qilish uchun biror soha yoki yo’nalishda “go-to-person”ga aylanish. “Go-to-person” - biror muammo yoki savol tug’ilganda murojaat qilinadigan odam: yo’nalish kattaroq kodning bir qismi, test qilish, biror freymvork, Kubernetes, Docker, biror usul va hokazo bo’lishi mumkin. Shu yo’nalishni topish va shu bo’yicha hamma suyanadigan, boradigan odamga aylanish odamning professional o’sishiga juda katta yordam beradi.
@farhodjon#growth
🌍 In November 2022, the world’s population reached 8 billion for the first time, doubling in just 48 years since 1974—a record pace in human history for global population growth. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, India gained over 13 million people—more than the total population of some countries. This rapid growth boosts its status as the planet’s most populous nation. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, Ethiopia recorded the world’s highest annual natural population increase, adding nearly 2.7 million people in a single year—more than many countries’ entire populations. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Leading Crypto VC Firms to Watch in 2023
Thanks for the feature! 💥
We're proud to be part of this ecosystem.
It's a privilege to be part of this Web3 future.
Let's keep building! ✨
#investment#community#growth
🌍 Over one million people are added to the world population roughly every five days. The fastest-growing regions are now in parts of Africa, where birth rates remain among the highest globally. ✨
#demographics⚡#growth⚡#continents⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
Good morning, good morning! ☀️ Looks like Darius had a good night's rest and is feeling even better than before.
———
Stage 2, Part 1 of the growth drive! Thank you all for your contributions to this - it's still in the works, albeit slowly!
Stage 2, Part 2 is in the works!
#art#growth#nsfw#hyper
Russia expects 3.9 percent GDP growth in 2024
📌 This is the result of a set of applied policies in the field of finance, infrastructure development, digitalization, building a knowledge economy, and improving the level of education of the population.
📌 "It was noted (at the APEC summit - ed.) that in comparison with other regions of the world in the economy (countries - ed.) APEC feel quite comfortable. GDP growth rates in APEC countries exceed the global averageaverage" - Russian Deputy Prime Minister Alexey Overchuk
#news#russia#nido_russia#economy#growth
https://t.me/nido_russia
🌍 The city of Lagos, Nigeria, is predicted to become the world’s most populous city by 2100. Rapid urban growth could bring its population over 80 million, surpassing today’s largest cities. ✨
#population⚡#growth⚡#megacities⚡#urbanization⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
TON is an up-and-coming powerhouse that we're absolutely stoked about⚡
In this video, TON's Head of Incubation, Justin Hyun, shares some exciting insights about Ton Foundation and its role in the #ecosystem.
While TON is younger than other significant Layer 1 blockchains, its rapid #growth and evolution has led it to become one of the hottest projects in the #crypto market in the last month, and it appears that next year will be exciting for TON.
In terms of transaction speed and versatility, TON Foundation remains ahead of other Layer 1 blockchains. In addition to a quick block validation time, the blockchain provides several advanced scalability features, such as sharding support.
Needless to say, we are a fan of this amazing #work and we can't wait to see the innovations that TON is going to bring to this space in the coming years.