Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
A light beige sphere rolling on the edge of an abstract golden arch, a giant pastel sphere, minimalist sculptural forms geometric objects composition, rendered in the style of Cinema4D, a light green background. Cinema4D rendering, close-up crop view, high resolution, macro photography, detailed textures --ar 2:3 --v 7
#sculpture
📣Midjourney prompts
A 3D fragment of rugged limestone floating in mid-air, covered with green moss, pale pink and orange corals, lichen, translucent quartz crystals, wildflowers with light blue petals, clean white background, soft warm natural lighting, photorealistic render, Octane Render, Cinema 4D --ar 3:4 --raw --v 7 --draft
by u4777486387
#sculpture
📣Midjourney prompts
A surreal collage of Plato and Aristotle floating in deep space, surrounded by glowing galaxies, cosmic nebulae, and celestial bodies. The background is an optical illusion of wavy black-and-white lines, blending into the cosmic void, creating a hypnotic, dreamlike atmosphere. A bold, glowing sun or planet in vibrant orange contrasts with the monochrome waves. Floating ancient Greek sculptures of Plato and Aristotle appear weightless, surrounded by philosophical symbols, sacred geometry, and ethereal cosmic dust. A mix of classical art, futuristic surrealism, and optical illusion, ultra-detailed, mesmerizing, and immersive --v 6.1 --ar 2:3 --s 50
by u8959768711
#sculpture
📣Midjourney prompts
an abstract shiny glimmering oblong metal goopy object floating in the middle of a dark sand dune with primary light focusing on the object --v 6.1
by formula1345
#sculpture
📣Midjourney prompts
Hyperrealistic photograph of a classical Greek marble statue with damaged smoothed face. The statue is positioned against a black background. The interplay of light highlights the texture of the statue and the damage give a dark gritty vibe --ar 4:5 --style raw --p vh9rjv1 --s 150 --v 6.1
by liamdomonkos
#sculpture
📣 Midjourney prompts
ea jar, Chinese style, divine phoenix decoration, hotel shelf, decoration, three-dimensional relief, white jade texture, transparent, elegant details --ar 1:2 --v 6.1
--
Sculptures with the theme Classic of Mountains and Rivers --ar 2:3 --v 6.1
by angus6930
#sculpture
📣 Midjourney prompts
Two large rocks in the shape of human heads, they look at each other and smile, a crescent moon between them, a dark blue sky, night photography, in the style of Aerial Photography, in the style of Wes Anderson, in the style of David LaChapelle, cinematic, shot on a film camera, Kodak film stock. --ar 105:128 --v 6.1
-
Two rock formations shaped like a woman's shoulders, a crescent moon in the dark blue night sky, in the style of Vincent Munier --ar 105:128 --v 6.1
by mr-indolent
#sculpture
📣 Midjourney prompts
A conceptual stack of stone building bricks, concrete and timber. It is set against a solid brown background to highlight the contrast between the diffeent objects and background. This art piece conveys creativity through geometric shapes and textured surfaces --v 6.1 --ar 57:85
by mr-indolent
#sculpture
📣 Midjourney prompts
thin sheet of glass monument standing upright in a black stone query. evening light reflecting from the glass onto the stones and creates rainbow like colors. the glass is about 50% of the image. in the style of a product art shooting --ar 3:4 --v 6.1
by timo_weiss
#sculpture
📣 Midjourney prompts
🧘Отдохнув от гаджетов и соцсетей, бесконечно понимаешь, сколько же в нашей жизни информационного и визуального мусора.
Минимализм во всём так прост и одновременно недосягаем.
an Majestic statue of Buddha, in the style of iris van herpen, franciszek starowieyski, peter holme iii, graceful movements, national geographic photo, caravaggesque chiaroscuro, landscapes in motion --c 20 --ar 3:4 --q 2 --style raw --sref 492309580 --p zww2nvy oiwf4m5 --s 1000 --v 6.1
by zhya666
#sculpture
📣 Midjourney prompts
A serene classical sculpture of a woman's head with closed eyes, adorned with soft, delicate pink flowers. The flowers gently float around her head, as if suspended in mid-air. The background is a minimalist light pastel blue, creating a dreamy, ethereal atmosphere. The entire scene should evoke a sense of calm, blending traditional art with modern aesthetics, featuring a balance between solid marble-like textures and the delicate, airy nature of flower petals --v 6.1
-
A beautiful woman Greek statue-like head, holding a rose in her hand, facing the camera, with her blonde hair in an updo, in the style of David LaChapelle and Mapplethorpe, a collage --v 6.1 --ar 7:8
by velskaa, cherryoasis
#sculpture
📣 Midjourney prompts