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

Резултати

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

Пребарај: #gattoverse

当前筛选 #gattoverse清除筛选
TONlines – News

@tonlines · Post #7240 · 16.05.2025 г., 13:37

Gatto Official Channel: Weekend Tournament Begins #GattoVerse#TON The GattoVerse Weekend Tournament kicks off, offering players the chance to win extraordinary prizes, including TON and various resources. The tournament starts on May 16 and ends on May 19. Participants are encouraged to join PvP battles and climb the leaderboard to secure top spots. Source: link @tonlines

TONlines – News

@tonlines · Post #6757 · 14.04.2025 г., 14:29

⚡️Gatto Official Channel: Dive into the GattoVerse NFT Adventure! #GattoVerse#TON GattoVerse welcomes the legendary NFT collection The Doge Pound with a trading volume of over $50,000,000. Join the event "Who let the dogs out?" and obtain new pets by purchasing Diamond Paws, which will transform into unique collectibles in two weeks. Source: link @tonlines

TONlines – News

@tonlines · Post #7186 · 13.05.2025 г., 09:04

⚡️Gatto Channel: Exciting Rewards with Lord Diamondog #GTON#GattoVerse Lord Diamondog has brought silver coins for $GTON, allowing players to purchase them and receive special rewards from the Hat Mouse Shop. Key prizes include treasury gold, spells, and resources for the future Lords of the GattoVerse, with bonus advantages for premium ticket holders. Source: link @tonlines

TONlines – News

@tonlines · Post #7025 · 02.05.2025 г., 13:32

Gatto | Official Channel: Battle in the GattoVerse #GattoVerse#GTON Gatto | Official Channel announces an exciting Weekend Tournament in the GattoVerse. Participants can win marvelous gifts, including various eggs, gold coins, and exclusive Gattoboxes. The tournament starts today and ends on May 5, with a special raffle using Crocottery Tickets. Source: link @tonlines

TONlines – News

@tonlines · Post #7138 · 09.05.2025 г., 12:38

Gatto | Official Channel (18+): Weekend Tournament Details #GattoVerse#Tournament GattoVerse is hosting a high-stakes Weekend Tournament starting today and ending on May 12. Participants in the PvP battles for $GTON can win prizes, including gold coins and exclusive Gattoboxes. Source: link @tonlines

TONlines – News

@tonlines · Post #6875 · 21.04.2025 г., 11:30

Gatto | Official Channel: A New Chapter with Nessie #Nessie#GattoVerse The GattoVerse was once again visited by Nessie, revealed not to be a monster but a protective mother of her species. After hatching her offspring, Nessie passed the responsibility of their care to the event participants who achieved 1000 damage points, rewarding them through the league. Source: link @tonlines

TONlines – News

@tonlines · Post #6766 · 14.04.2025 г., 18:36

Gatto: Upcoming Mine Rescheduling Announcement #Aetherian#GattoVerse Gatto | Official Channel announces a rescheduling of the mine due to a portal opening in the Aetherian world. The next mine event, offering two opportunities with rewards, is scheduled for April 24th. Source: link @tonlines

TONlines – News

@tonlines · Post #6743 · 13.04.2025 г., 18:08

⚡️GattoVerse: A Star Marks a New Beginning #GattoVerse#Aetherian The GattoVerse is on the brink of transformation as a new star promises to illuminate the skies, potentially creating a portal to the ancient Aetherian world. This event could turn legendary tales into reality, and merchant Hat Mouse is poised to seize the moment. Source: link @tonlines