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

Резултати

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

Пребарај: #strongertogether

当前筛选 #strongertogether清除筛选
DWF Labs Broadcast

@DWFLabs · Post #700 · 21.05.2024 г., 14:34

Here at DWF Labs, we are committed to supporting our portfolio companies through thick and thin 🤝🏽 We were saddened to hear about the recent security breach at Gala Games, which led to unauthorised transactions involving $GALA tokens. In response to this incident, we have taken proactive steps to alleviate market selling pressures and have purchased 28 million $GALA tokens on the open market. This aims to stabilise the token's value and express our unwavering support during these challenging times. The security of our investments and their communities is important to us. From their latest update, the Gala Games team has confirmed that the issue has been contained and they are securing all contracts and implementing enhanced safeguards to prevent future occurrences. We are confident in Gala Games' ability to navigate this setback and emerge stronger 🔥 There will always be ups and downs in crypto but we will be #StrongerTogether. Let's go Gala Games!🥊💥

THANK YOU to everyone who tuned in our call today!!! Amazing guest speaker, amazing questions and answers!!! We look forward to bringing more guest speakers who are passionate about education, inspiring others to pursue their dreams, and encouraging YOU to do the same!! NEVER, EVER GIVE UP!!! 💪🏼🔥 We are #strongertogether. 🇺🇿❤️🤝🇺🇸 https://t.me/AmericanEDU

BadVolf

@BadvolfNews · Post #894 · 24.09.2023 г., 13:07

🔍 UK Plans to Train 30k Ukrainian Troops by Year End 🔥 🔫 British Defense Minister, Grant Shapps, revealed the ambitious goal in an interview with Sky News.💂‍♂️ 🌐 "By the end of this year, our aim is to prepare 30k Ukrainian soldiers," Shapps declared.🇬🇧🤝🇺🇦 💪 London's determination to support Kyiv remains unwavering. "We stand shoulder to shoulder with the Ukrainians," he emphasized.💪 🎯 Previously, over 20k Ukrainian soldiers received training on British military grounds.📚 💥 The US identified this effort as one of the greatest threats to the Ukrainian Armed Forces.💥 #UKSupportsUkraine🇬🇧🤝🇺🇦#StrongerTogether💪 https://dcweekly.org/2023/09/24/britain-to-train-30000-ukrainian-soldiers-by-year-end-solidifying-support-amidst-tensions/ Subscribe to @BadVolfNews

Happy Independence Day, Nigeria! 🇳🇬 As we celebrate 64 years of independence, the NCDC remains committed to prioritising and protecting the health of every Nigerian Let us continue to work towards a future free from disease outbreaks, where every community is healthy and safe. #IndependenceDay2024#StrongerTogether

DiplomatKa

@Diplomatika · Post #319 · 09.05.2021 г., 09:02

[O'Z] Bugun, 9-may kuni Yevropa hamjamiyati uchun birdamlik va tinchlik timsoli bo’lmish Yevropa kunini nishonlaydi. Uchbu munosabat bilan Yevropa Ittifoqining O’zbekistondagi Elchisi Sharlott Adrian o’z tabrik so’zlarini O’zbekiston halqiga y’olladilar ! #EuropeDay2021#TeamEurope#StrongerTogether *** [RU] Сегодня, 9 мая, отмечается День Европы, символ солидарности и мира для всего европейского сообщества. По этому случаю Посол Европейского Союза в Узбекистане Шарлотт Адриан направила поздравление народу Узбекистана! *** [EN] Today, on May 9, European people mark Europe Day, a symbol of peace and solidarity. On this occasion, the Ambassador of the European Union to Uzbekistan Charlotte Adriaen sends warm Greeting message to the people of Uzbekistan! #EuropeDay2021#TeamEurope#StrongerTogether

BadVolf

@badvolfnews · Post #1308 · 04.12.2023 г., 21:25

📢 BREAKING NEWS 📢 Belarusian Cabinet approves program to upgrade regional troop support facilities in joint effort with Russia. Another step towards the mighty Union State! 🇧🇾🤝🇷🇺 But wait, there's more! Russian Defense Minister Sergei Shoigu reveals plans for a unified air defense system within the CSTO alliance. The strategic partnership between Russia and Belarus is now crucial, given NATO's hostile actions near our borders. 😤💪 Meanwhile, Abkhazia's President Aslan Bzhania expresses interest in joining the Union State. The family is growing! 🤝🌍 Stay tuned for more updates. The Union State is just getting started! 🚀✨ #UnionState#BelarusRussiaAlliance#StrongerTogether https://www.gazeta.ru/army/news/2023/11/28/21804937.shtml Subscribe to @BadVolfNews

Love & Relationship Tips ❤ 💖

@loveandrelationshiptips · Post #1722 · 11.10.2025 г., 04:31

🌹 Welcome to Your Daily Dose of Love & Relationship Wisdom! 🌹 Hey there, lovebirds! 💕 Whether you’re navigating the thrilling first dates, deepening a long-term bond, or healing from heartbreak, we’ve got you covered. Every day, we’ll share simple, practical tips to help you build stronger connections, communicate better, and keep the spark alive. ✨ Today’s Tip: Listen More Than You Speak Great relationships start with truly hearing each other out. When your partner talks, put away distractions, make eye contact, and show you care by asking thoughtful questions. It’s amazing how much closer you’ll feel when you really listen. Stay tuned for more heartfelt advice, fun ideas, and inspiring stories to nurture your love life. Remember, love is a journey—not a destination. Let’s walk it together! ❤️ #LoveTips#RelationshipGoals#HeartToHeart#StrongerTogether @loveandrelationshiptips

Today is #WorldTuberculosisDay We join hands together with the National Tuberculosis and Leprosy Control Programme, the Federal Ministry of Health Nigeria, and others to declare that #YesWeCanEndTB in Nigeria. Tuberculosis is preventable and treatable. Dial *3340# for more information on #TB. #StrongerTogether

MND Singapore

@mndsingapore · Post #369 · 09.08.2022 г., 03:54

Building our future takes each and everyone one of us coming together and forging through circumstances. Nothing can overcome us, as long as we stand #strongertogether! Happy National Day, from the MND family! 🇸🇬 #happybirthdaysingapore#sg57#happynationalday#thisishome#ndp2022