Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
🌎 Ancient Egypt’s ability to make “Egyptian blue,” the first synthetic pigment, was lost for centuries. This stable, vivid blue was made from copper, silica, and lime, fired at high temperatures. Modern chemists only rediscovered the process in the early 19th century using advanced analysis of ancient artifacts. ✨
#history⚡#archaeology⚡#chemistry
👉subscribe Interesting Planet
👉more Channels
🌎 The pyura chilensis, also known as the “living rock,” is a sea creature found on Chile’s coast that looks like a stone but bleeds bright red when cut. Its tunicate body is actually a filter feeder packed with vanadium, a rare element in animals. ✨
#ocean⚡#animals⚡#chemistry
👉subscribe Interesting Planet
🌍 In Africa’s Lake Natron, minerals in the water turn it bright red during the dry season. The lake’s extreme chemistry preserves animal remains, creating eerie natural “statues.” ✨
#lakes⚡#Africa⚡#chemistry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
Today in history.
On March 6, 1869, Russian chemist Dmitri Mendeleev presented the first periodic table of elements, titled "The Dependence Between the Properties of the Atomic Weights of the Elements," to the Russian Chemical Society. He organized 63 known elements by atomic weight, leaving gaps for undiscovered elements like gallium and germanium.
@googlefactss#chemistry#history#todayinhistory
[read more...]
🌎 In 1867, Swedish chemist Alfred Nobel invented dynamite by stabilizing volatile nitroglycerin with an absorbent clay called kieselguhr. This made blasting much safer for construction and mining. Nobel later used his dynamite fortune to establish the Nobel Prizes in 1895. ✨
#inventions⚡#chemistry⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The accidental invention of safety glass happened in 1903, when French chemist Édouard Bénédictus dropped a glass flask coated with plastic cellulose nitrate. Rather than shattering, the glass cracked but held together, inspiring shatter-resistant windshields. By 1927, safety glass became standard in automobile manufacturing. ✨
#inventions⚡#chemistry⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 In the dark waters of the Black Sea, ancient bacteria can “eat” toxic hydrogen sulfide gas, turning it into harmless sulfate. This vital process keeps deep sea life possible in these oxygen-poor zones. ✨
#bacteria⚡#chemistry⚡#ocean
👉subscribe Interesting Planet
🌎 Ancient Greek fire, known as "Greek fire," was a weapon that could burn even on water. This flammable liquid, projected from tubes, terrified enemies at sea and kept its formula a closely guarded secret, lost to history. ✨
#history⚡#chemistry⚡#warfare
👉subscribe Interesting Planet
Russia leads at the 60th International Mendeleev Chemistry Olympiad in Moscow, winning 7 gold and 8 silver medals. All 15 Russian participants received awards, showcasing top university-level skills. Vice Premier Chernyshenko called the result outstanding, while Minister Kravtsov highlighted systematic preparation. The Olympiad is part of the Science and Technology Decade running until 2031. This victory underscores Russia’s strength in chemistry education and research.
#Russia#MendeleevOlympiad#Chemistry#Science
The main news of Russia and the world ishere.
🪐 Encircling the young star TW Hydrae, a vast protoplanetary disk glows with mysterious gaps and spiral patterns sculpted by the formation of new worlds. Observations with ALMA revealed complex chemical fingerprints in the disk, including cyanide compounds that could play a role in the origins of life. ✨
#TWHydrae⚡#protoplanetary⚡#chemistry
👉subscribe Universe Mysteries