Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🌎 An ancient mystery lingers at the center of our galaxy—a supermassive black hole called Sagittarius A*. Its powerful gravity bends space and time, hiding beyond a swirling cloud of stars and gas. This invisible giant shapes the Milky Way, anchoring everything around it with immense, unseen force. ✨
#space⚡#blackhole⚡#universe
👉subscribe Interesting Planet
🌎 In 2020, astronomers detected a mysterious object named “The Cow,” a fast and extremely bright stellar explosion. Unlike normal supernovas, “The Cow” rapidly peaked in brightness, confounding scientists. Follow-up observations revealed it was likely the birth of a black hole or neutron star—providing a rare view of a star’s collapse in real time. ✨
#astronomy⚡#supernova⚡#blackhole
👉subscribe Interesting Planet
👉more Channels
BlackHole
Music Player made with Flutter
Features
Best Streaming Quality (320kbps)
Music Search
Trending Songs
Support 15+ music languages
Local and Global Top Spotify songs
Add Songs to Favorite
Playlists support
Import Playlists from Spotify
Sleep timer
Lyrics Support
Listening history record
Dark mode / accent color
Download for offline play (320kbps with ID3 tags)
Play Online as well as Offline Songs
Queue Management
Auto Update Check
Cache support
No Subscription
No Ads
More to come...
Download https://github.com/Sangwan5688/BlackHole/releases
Channel @blackhole_channel
Group https://t.me/joinchat/fHDC1AWnOhw0ZmI9
#BlackHole#Music#Player
🌎 At the center of our Milky Way galaxy lies Sagittarius A*, a supermassive black hole around 4 million times the mass of the Sun. It exerts a powerful gravitational pull, causing nearby stars to orbit at incredible speeds—some over 5,000 kilometers per second. ✨
#astronomy⚡#blackhole⚡#galaxy
👉subscribe Interesting Planet
👉more Channels
🪐 The galaxy NGC 1277 in the Perseus constellation harbors an ultramassive black hole that makes up a staggering 14% of its entire mass—a proportion far greater than in any typical galaxy. This enigmatic black hole has puzzled scientists, as such a gigantic ratio defies cosmic norms and hints at a forgotten chapter in the history of galactic evolution. ✨
#galaxies⚡#blackhole⚡#mystery
👉subscribe Universe Mysteries
🪐 The dusty core of the elliptical galaxy Centaurus A (NGC 5128) hides a colossal jet of high-energy particles, launched from a supermassive black hole and stretching over 1 million light-years into intergalactic space. X-ray and radio images reveal this jet carving through the surrounding gas, shaping the galaxy’s strange appearance and fueling vast lobes that glow in the cosmic void. ✨
#CentaurusA⚡#blackhole⚡#galaxy
👉subscribe Universe Mysteries
🪐 In the galaxy SDSS J135154.46+132719.1, astronomers have observed a striking phenomenon: a supermassive black hole that was caught being "kicked" out of its galaxy at nearly 7.5 million kilometers per hour. This cosmic eviction is thought to be caused by the merged black holes’ gravitational waves pushing the giant object away—an extreme event where the very heart of a galaxy is flung into intergalactic space. ✨
#phenomena⚡#galaxy⚡#blackhole⚡#nasa⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🌎 Deep within the constellation Cygnus, the black hole V404 Cygni occasionally unleashes powerful outbursts, ejecting matter at near light-speed in opposing jets. These rare events are so energetic that the black hole briefly outshines its entire host galaxy, offering a fleeting glimpse into the turbulent ballet around stellar remnants. ✨
#blackhole⚡#cygnus⚡#jets
👉subscribe Universe Mysteries
🪐 In the Perseus Cluster, a supermassive black hole at the center of the galaxy NGC 1275 sends out powerful sound waves that ripple through the surrounding gas. These cosmic vibrations have wavelengths so vast—spanning around 30,000 light-years—that they produce the deepest note ever detected, 57 octaves below middle C, making it a real, albeit inaudible, “song” of the universe. ✨
#PerseusCluster⚡#blackhole⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries