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

Резултати

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

Пребарај: #podol

当前筛选 #podol清除筛选
DruschbaFM - English

@druschbaFm_en · Post #52019 · 13.03.2025 г., 07:57

⚡️🇷🇺🇺🇦⚡️ Two Majors #Summary for the Morning of 13 March 2025; 06:46 (GMT+3)⚡️ 🎯 Enemy Sources reported another wave of strikes using FABs with UMPC, OTRK, and 'Geranium' drones. Explosions were reported in the #Sumy, #Kherson, #Nikolayev, #Odessa, #Khmelnitsky, #Dnepropetrovsk, #Zaporozhye, #Kiev and #Cherkassy regions. 🔹 In #Kursk Region, the key event was the liberation of #Sudzha.🗺👆 Russian forces have full control of the city, conducting clearing operations against remaining enemy fighters hiding in basements and shelters. The settlements of #Podol and #Melovoy have also been secured. Dozens of civilians, who had survived under enemy occupation, were evacuated from the liberated villages. The AFU continues launching long-range US MLRS strikes on the region. Yesterday morning, the AFU attacked a feed factory in the village of #Kozyrevka, Bolshesoldatsky district, killing four employees and seriously wounding another. The Supreme Commander visited the command post of the Russian Grouping, setting the task of expanding the buffer zone along the border and fully defeating enemy forces in the #Kursk region. 🔹 In #Sumy Region, meanwhile, clashes continue along the #Novenkoye – #Basovka axis. 🔹 In #Liman Section, fighting is ongoing towards #Novoye and south of #Yampolovka, where the AFU is offering organised resistance and bringing in reserves. 🔹 In #Toretsk, the situation remains unchanged. The enemy continues infiltrating units into the urban area. While the AFU has no chance of altering the situation, eliminating the enemy groups that have managed to break through consumes time and resources. 🔹 In #Pokrovsk Direction, Russian forces are attacking in the areas of #Uspenovka, #Udachnoye, and #Kotlino. Heavy fighting continues in #Peschanoye and #Shevchenko, with no significant territorial gains for a long time. The enemy has reinforced this sector with reserves, including units trained in EU countries, and is suffering heavy losses in counterattacks. South of #Yasenevo, Russian forces are also attacking to straighten the front line. 🔹 On the #Vremyevka Ledge, Russian forces have raised the flag over the northern part of #Dneproenergiya, confirming the capture of the settlement. 🔹 On the #Zaporozhye Front, intense combat continues in the #Orekhov direction and on the approaches to #Shcherbaki. Russian forces are making progress, and positive developments from this axis are expected. 💥 In #Belgorod Region, the AFU Nazis continues their attacks. In the hamlet of #Tserkovny, Belgorod district, a drone struck a civilian car. Another vehicle was attacked by an FPV drone in the village of #Terebreno, Krasnoyaruzhsky district. A social facility was hit in #Tishanka, Volokonovsky district. In #Shvedunovka, Valuysky district, a drone detonated near a private house. 💥 In the #DPR, in #Nikolskoye, Volnovakha municipal district, a man born in 1975 was killed by the detonation of an explosive device. Near a reservoir in #Ilovaysk, a 17-year-old boy was injured due to the detonation of an explosive device. 💬Welcome to Military Chat; 🇬🇧Battle Maps 📱 Join GLOBAL DEPTH to boost your TG Feed GLOBAL DEPTH from #HK This channel aims to unite interested individuals from around the world in an attempt to connect the dots. Subscriber participation is always welcome here and in the channel's Chat Group.