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 слични објави

Пребарај: #tondns

当前筛选 #tondns清除筛选

Why collect SBT and XP from🙏TON Society? Let us remind you that SBT (Soulbound Token) is an NFT that is tied to your wallet, it cannot be traded or sold, which makes your wallet unique if it stores SBT NFT. What is it for? SBT NFT is a kind of “identity confirmation”, but only anonymous. SBT makes it clear to the sender that he is dealing with the right recipient and the right person behind him. Including when it comes to awards for contributions to the development of The Open Network. Such rewards can be obtained for activities within the Open League, they are displayed in your TON Society profile. What will SBT and XP owners get? Already, many people are collecting these achievements expecting to receive a reward in the future, but few people know how it works and what they can count on. ❤️Open League and SBT • SBTs are issued (minted) by the TON Society for contributions to the development of the TON blockchain community - for example, for participating in competitions and attending AMA sessions, attending conferences and meetups. • SBTs are issued by projects that receive incentives and grants through the Open League. 🫰Experience Points (XP) will become reputation points and will be converted into $TON • XP points at a 1:1 ratio to $TON , can be exchanged for $TON at any time. • Time-based formula affects the exchange rate - if $XP tokens are redeemed before March 31, 2025, the conversion will be at a less favorable rate. • On March 31, 2025, 1 XP will be equal to 1 $TON • SBT assumes a constant increase in XP income for inviting friends, purchasing Telegram Premium or TON DNS. 🔝TON Society will become the new public profile of the TON member, recognizing and rewarding everyone's achievements and contributions. #TON#Toncoin#TheOpenLeague#MassAdoption#TONSociety#TONDNS#SBT#NFT ⚡️Boost | 🎞YouTube |🌐Twitter