Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Berachain's Infrared Raises $14 Million
Berachain's liquid staking protocol, Infrared, successfully raised $14 million in a Series A token round. The funding aims to support its DeFi initiatives. Read more here: The Block
#DeFi#Berachain#Infrared#Crypto#Investments#Funding#VC
🪐 In 2023, astronomers discovered a free-floating planet called WISEA J110125.95+540052.8, drifting alone about 100 light-years from Earth. Unlike planets tied to stars, rogue planets like this one travel through the galaxy in darkness, warmed only by the faint heat left over from their formation and detectable mainly in infrared light—a reminder that not all worlds need a sun to wander the cosmos. ✨
#rogueplanets⚡#infrared⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The Milky Way may be home to countless rogue planets—worlds that travel alone, not bound to any star. One such loner, called WISEA J083011.95−614123.5, was spotted using infrared telescopes as it drifts in perpetual night, offering a glimpse into what planets look like when cut off from the warmth and light of a sun. ✨
#rogueplanets⚡#infrared⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Astronomers estimate there could be billions of rogue planets—planets not bound to any star—drifting through our galaxy in darkness. One example, PSO J318.5-22, floats alone about 80 light-years from Earth, glowing faintly in infrared because it holds onto leftover heat from its formation, even though it has no sun to warm it. ✨
#rogueplanets⚡#galaxy⚡#infrared⚡#nasa⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The rogue planet PSO J318.5-22, located about 80 light-years away in the constellation Capricornus, drifts alone through space without a star to call home. Unlike planets that orbit a sun, PSO J318.5-22 glows faintly in infrared from the warmth left over from its formation, making it a true cosmic wanderer and one of the few planetary-mass objects visible in the dark between the stars. ✨
#rogueplanets⚡#exoplanets⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The James Webb Space Telescope has revealed distant galaxies like MACS1149-JD1 forming stars much earlier than expected, showing that galaxy building blocks were already in place just 500 million years after the Big Bang. By capturing infrared light, Webb can see through cosmic dust and uncover the birth of some of the universe’s first stars, helping scientists understand how the cosmos evolved from darkness to a landscape filled with galaxies. ✨
#Webb⚡#galaxies⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The James Webb Space Telescope has revealed the most detailed images yet of the galaxy cluster SMACS 0723, showing thousands of galaxies and ancient starlight that traveled over 4.6 billion years to reach us. Webb’s infrared vision lets us peer through dust and see cosmic structures, such as warped arcs of light caused by gravitational lensing—where the cluster’s mass bends and magnifies even more distant galaxies hiding behind it. ✨
#galaxies⚡#infrared⚡#lensing⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The James Webb Space Telescope stunned astronomers by capturing images of the faintest, most distant galaxies ever seen—like GLASS-z13, which formed when the universe was only about 300 million years old. Webb’s infrared eyes pierce cosmic dust, making it possible to observe galaxies and stars that existed just after the Big Bang, revealing clues about how the first stars and galaxies came to life. ✨
#webb⚡#galaxies⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Near the center of our Milky Way, a cluster of young, massive stars known as the Quintuplet Cluster exists amid clouds of dust, virtually hidden from optical telescopes. Infrared observations have revealed these colossal stars, including the enigmatic "Pistol Star," which burns with a luminosity 1.6 million times brighter than our Sun and sheds mass in powerful, mysterious outbursts. ✨
#QuintupletCluster⚡#PistolStar⚡#infrared
👉subscribe Universe Mysteries
🚀 Infrared to Unlock 27.64 Million Tokens on April 17
Infrared (IR) is set to unlock approximately 27.64 million tokens on April 17 at 0:00 UTC+8. According to ChainCatcher, this information comes from the Web3 asset data platform RootData's token unlocking data. The unlocked tokens are valued at around $1.01 million.
#Infrared#tokenunlocking#Web3#ChainCatcher#RootData#cryptocurrency#April17#digitalassets