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

Резултати

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

Пребарај: #globaltrends

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

@CryptoM · Post #64981 · 10.04.2026 г., 12:48

🚀 Economist Win Thin Reflects on Global CPI Trends Economist Win Thin has observed that, in retrospect, the Consumer Price Index (CPI) data for March in most countries worldwide was slightly below expectations, with the exception of the United States. According to Jin10, many other countries are increasing fuel subsidies to alleviate the impact on consumers. However, Thin warns that this approach may lead to significant fiscal burdens, making it unsustainable in the long term. #Economist#CPI#GlobalTrends#FuelSubsidies#FiscalBurden#Inflation

EdgeMarket.AI 📣

@edgemarketai · Post #7987 · 09.02.2026 г., 19:28

🌍 One question. Global consequences. Will Russia and Ukraine reach a ceasefire by March 31, 2026? Diplomacy, pressure, fatigue — or escalation? Drop your take 👇 https://edgemarket.ai/bnb/social-media/Russia%20x%20Ukraine%20ceasefire%20by%20March%2031,%202026/statistics/69830479ff612403d86bf273 #Geopolitics#Ceasefire#WorldNews#GlobalTrends#ConflictAnalysis#FutureEvent

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9653 · 03.12.2025 г., 08:21

#The_Fortune🇺🇸📕[PDF]⬇️ #December2025 #January2026 #Monthly_Magazines For learning, for free(dom). @backupofmagazines Global coverage this week tracks how rising tech power reshapes markets and geopolitics as China accelerates drug manufacturing, automation and green innovation with implications for global supply chains amid growing #Geopolitics tension. U.S. markets confront an expanding #AI boom, from Anthropic’s trust-first model to questions around Nvidia’s dominance, while investors chase new strategies in an increasingly volatile #MarketWatch environment. Culture and consumer shifts surface in Roblox’s evolution, the booming beauty sector and wellness travel trends. Meanwhile climate action, urban sustainability and energy transitions intensify worldwide under mounting #ClimateCrisis pressure, defining a rapidly changing global landscape shaped by #GlobalTrends.

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9618 · 26.11.2025 г., 02:12

#The_Barron's 🇺🇸📕[PDF]⬇️ 24 #November2025 #Weekly_Magazines For learning, for free(dom). @backupofmagazines Europe’s renewed market momentum anchors this Barron’s issue, where analysts see brighter days ahead amid rising profits and shifting geopolitics—an outlook shaped by #MarketWatch forces and #GlobalTrends. Nvidia’s strong guidance fuels confidence in the #AI boom, even as investors navigate #Volatility across equities and buffer ETFs. Caution rises around India’s IPO wave, reinforcing a broader #RiskManagement mindset. With bond vigilantes returning and central-bank uncertainty growing, the magazine highlights why disciplined strategy remains essential in today’s #Finance landscape.

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9561 · 17.11.2025 г., 03:17

#The_Science🇺🇸📕[PDF]⬇️ 13 #November2025 #Weekly_Magazines For learning, for free(dom). @backupofmagazines This issue dives into breakthroughs reshaping biology and energy as researchers confront rising geopolitical limits. From #AI-driven epigenetics to #SyntheticBiology advances, the issue tracks how innovation pushes ahead despite tensions over China-US research ties. New micro-robots navigating the bloodstream and faster-charging batteries highlight a surge in #DeepTech momentum. Climate resilience, #PandemicPreparedness, and EU chemical reforms underscore global policy stakes. Studies on dog domestication, brown dwarfs, and marine recovery after extinction broaden the scientific lens. A reminder that #ScienceMatters even as politics shift—innovation continues to define our shared future. #TechNews#GlobalTrends#ResearchUpdates

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9463 · 03.11.2025 г., 03:27

#The_National_Geographic🇺🇸📕[PDF]⬇️ #November2025 #Monthly_Magazines For learning, for free(dom). @backupofmagazines This issue tours big frontiers: a colossal #NuclearFusion tokamak in France promises star power on Earth; botanists curate the world’s deadliest garden; a teenage Sherpa resets who belongs on alpine peaks; macro art peers through a bug’s eye; new science reframes adult #ADHD; crested gibbons show robotlike dances; wildfire imagery from the #SierraNevada; archaeologists ink themselves to decode ancient tattoos; and medics test human hibernation for deep-space care. Essential reading for explorers and pragmatists alike. #NationalGeographic#Climate#Energy#Biodiversity#Wildfire#Photography#Neuroscience#Space#Innovation#Science#Sustainability#Tokamak#Fusion amid accelerating #AI research and #GlobalTrends, shaping tomorrow’s decisions.