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

Резултати

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

Пребарај: #navaloperations

当前筛选 #navaloperations清除筛选
Crypto M - Crypto News

@CryptoM · Post #65150 · 11.04.2026 г., 12:55

🚀 U.S. Navy Ships Navigate Hormuz Strait Without Coordination with Iran On April 11, U.S. officials announced that several U.S. Navy vessels traversed the Strait of Hormuz on Saturday. According to BlockBeats, the passage was conducted without coordination with Iranian authorities. The Strait of Hormuz is a strategic waterway, and such movements often draw international attention due to the geopolitical tensions in the region. #USNavy#HormuzStrait#Iran#Geopolitics#NavalOperations#InternationalRelations#MiddleEast

Crypto M - Crypto News

@CryptoM · Post #65296 · 12.04.2026 г., 15:20

🚀 Iran Intercepts U.S. Warships Near Strait of Hormuz Iran's navy reported intercepting two U.S. warships near the Strait of Hormuz as they attempted to enter the Persian Gulf during a ceasefire. According to NS3.AI, the vessels were identified as the Frank E. Petersen and Michael Murphy. Iran alleged that the ships aimed to project an image of a successful passage and potentially influence ongoing negotiations between the U.S. and Iran. #Iran#USNavy#StraitOfHormuz#Military#NavalOperations#PersianGulf#Geopolitics#InternationalRelations

Crypto M - Crypto News

@CryptoM · Post #65096 · 11.04.2026 г., 00:45

🚀 Iran Faces Challenges in Reopening Hormuz Strait Due to Unlocated Mines Iran is encountering difficulties in fully reopening the Strait of Hormuz as it struggles to locate all the mines it previously deployed. According to Odaily, the country also lacks the necessary capabilities to effectively clear these mines. This situation poses significant challenges for Iran in ensuring the safe passage of vessels through this critical waterway. #Iran#HormuzStrait#Mines#MaritimeSafety#Shipping#NavalOperations#InternationalTrade#Geopolitics

Crypto M - Crypto News

@CryptoM · Post #65313 · 12.04.2026 г., 22:02

🚀 CENTCOM to Enforce Blockade on Iranian Maritime Traffic CENTCOM has announced a blockade on all maritime traffic entering and leaving Iranian ports, effective April 13 at 10 a.m. ET. According to NS3.AI, this directive applies to vessels of any flag or ownership within Iranian coastal waters, including ports in the Arabian Gulf and the Gulf of Oman. Ships transiting the Strait of Hormuz to or from non-Iranian ports will maintain freedom of navigation. CENTCOM has not specified the duration of the blockade and stated that further guidance will be provided. #CENTCOM#Iran#Maritime#Blockade#StraitOfHormuz#ArabianGulf#GulfOfOman#NavalOperations

Crypto M - Crypto News

@CryptoM · Post #65342 · 13.04.2026 г., 00:52

🚀 UK Declines Participation in US Strait of Hormuz Blockade Informed sources have revealed that the United Kingdom will not join the United States in a blockade operation in the Strait of Hormuz, following an announcement by U.S. President Donald Trump that the US Navy would block the waterway. According to NS3.AI, a UK government spokesperson emphasized the country's commitment to freedom of navigation and stated that the UK is collaborating with France and other partners to form a coalition aimed at safeguarding the route. #UK#US#StraitOfHormuz#Blockade#NavalOperations#FreedomOfNavigation#InternationalRelations#Coalition#MaritimeSecurity