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

Резултати

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

Пребарај: #pixelswap

当前筛选 #pixelswap清除筛选

💣The Largest DeFi Airdrop Event in History on TON is here! Are you ready?✨ A total of over 10,000,000+ $PIX will be distributed and we are happy to remind everyone that DEX tokens have significant value. This airdrop event brings you incredible reward opportunities, and what’s even better is that everyone has a chance to win rewards. Whether you are new to the TON ecosystem or a veteran of TON DeFi, this event invites all influencers to shape the future of TON DeFi with PixelSwap. Here is the instruction how to participate and increase your chances: Read the article 📖 #DeFi#Airdrop#DEX#TON#PixelSwap

💎PixelSwap — The First Weighted Pool DEX on TON #PixelSwap is a distinguished modular #DEX built on the #TON blockchain. Audited by a leading global agency, PixelSwap prioritizes smart contract security as a cornerstone of the project, demonstrating this commitment through significant advancements in security infrastructure. PixelSwap's innovative layered architecture supports a variety of algorithms, including weighted pools and LBP launches. Moreover, PixelSwap facilitates atomic transactions, enabling the execution of complex DeFi scenarios. The team aspires to be one of the most secure projects in the #DeFi space and to contribute to the overall security development of the TON ecosystem. 💎PixelSwap x 🍅Tomarket Recently #PixelSwapbecomes a partner of Tomarket, the incentive-driven platform guiding Web2 users seamlessly into Web3 through gaming, earning, and trading! 😄 With over 42M users and 12M connected wallets, #Tomarket is redefining the Web3 experience by offering an all-in-one ecosystem where users can engage in games, earn tokens through activities, and trade assets across multiple chains — all on a single platform. 💱 By combining PixelSwap's advanced liquidity and trading solutions with Tomarket’s extensive user base, they are set to deliver a powerful ecosystem that enables users to not only swap but also access meaningful rewards and explore deeper engagement opportunities. This collaboration creates an ideal path for users to learn, earn, and stay involved in #Web3. The $PIX Token #TGE in Q4 2024! The team has set aside a substantial allocation of $PIX tokens for the community! Be sure to follow @PixelSwap_io and join the community for the latest updates on the Pre-TGE Airdrop Arena! 💎$PIX token serves as the utility token for #PixelSwap, the only modular #DEX that supports both Weighted Pools and Atomic Swaps on #TON. Join ⚔️Pixel Airdrop Arena and stay tuned for more updates! Official Links⬇️ 🔗LayerPixel: Website | X | Channel | Community | Medium | Bot 🔗PixelSwap: Website | X | Channel | SWAP | Pool 🔗PixelDAO: X | Forum | Chat

⏺PixelSwap Farming Pool in🍅Tomarket #PixelSwap recently partnered with the well-known social platform Tomarket, which allows Web2 users to easily transition to Web3 through games, earnings and trading. There is a new farming pool available in 🍅#Tomarket app where you can get a share of $PIX depending on how much $TOMA you contribute to the pool. The pool starts tomorrow at 10:00 UTC🕓 ✖️Use TOMA to get PIX! #TOMA#PIX#earn#farming