TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #22 · 19 јан.

Заметка начинающим, которые часто сталкиваются с подобной непоняткой. Ситуация следующая, есть список файлов: 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

Hashtags

Резултати

Пронајдени 6 слични објави

Пребарај: #sgweathergrams

当前筛选 #sgweathergrams清除筛选
NEA Singapore

@NEASingapore · Post #589 · 12.07.2023 г., 01:02

Did you manage to catch these pastel-coloured altocumulus clouds at sunset? When the sun is at a low angle on the horizon, sunlight travels across a longer distance through the atmosphere before reaching our eyes. As a result, blue colours are scattered by atmospheric particles, leaving behind brilliant hues of pink, orange and yellow. 📷: peiqiitohh #SGWeathergrams#WeatherWednesday

NEA Singapore

@NEASingapore · Post #565 · 14.06.2023 г., 00:31

If you were in the Newton area on 25 May, you may have spotted this huge woolly blanket in the sky! This blanket of dense clouds was formed as the top of a cumulonimbus cloud collapsed following strong thunderstorms across Singapore earlier that morning. Named “cirrus spissatus”, these rarer upper atmosphere clouds are thicker and denser, and would block out the sun. The Latin word “spissatus” in its name describes its thicker appearance. 📷 Photo by _quietude__ #SGWeathergrams#WeatherWednesday

NEA Singapore

@NEASingapore · Post #78 · 15.07.2020 г., 00:30

The mesmerising patterns formed by these beautiful stratocumulus clouds, seem to be reminding us to keep a safe distance from each other as we go about our daily activities. Tag us in your #SGWeathergrams on Instagram so that we can share your beautiful captures with others! #WeatherWednesday 📷: infectiousj

NEA Singapore

@NEASingapore · Post #105 · 22.09.2020 г., 07:45

Hello Halo! Did you spot it this afternoon? These faint coloured rings encircling the sun are formed by the refraction of the light through ice crystals in high-level clouds under relatively clear conditions. #SGWeathergrams#SGWeather

NEA Singapore

@NEASingapore · Post #90 · 12.08.2020 г., 00:30

While an impending thunderstorm looms, blue skies and fluffy clouds shine through in the distance. Tag us in your #SGWeathergrams posts on Facebook & Instagram so we can share it on #WeatherWednesdays. :) 📷: siewjunjie

NEA Singapore

@NEASingapore · Post #579 · 05.07.2023 г., 01:01

#WeatherWednesday#throwback to the sunrise on 17 Jun, when we were greeted by this beautiful scattering of cirrocumulus stratiformis clouds. The Latin word “stratiformis” means “stretched out”, referring to its irregular, dotted, blanket-like appearance. 📷 Photo by knifematchneedle #SGWeathergrams