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

Резултати

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

Пребарај: #computingpower

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

@CryptoM · Post #64766 · 09.04.2026 г., 20:24

🚀 AI TRENDS | OpenAI Claims Superior Computing Power Over Anthropic OpenAI has informed investors that its computing capabilities surpass those of Anthropic. According to Jin10, this assertion highlights OpenAI's confidence in its technological advancements and competitive edge in the AI industry. The statement comes amid growing interest and investment in artificial intelligence, as companies strive to enhance their computational power and efficiency. OpenAI's claim may influence investor perceptions and decisions, potentially impacting market dynamics and the competitive landscape within the AI sector. #AI#OpenAI#Anthropic#ArtificialIntelligence#ComputingPower#TechTrends#Investment#AIIndustry#MarketDynamics#Innovation

Crypto M - Crypto News

@CryptoM · Post #65247 · 12.04.2026 г., 09:19

🚀 STOCKS | Galaxy Securities Highlights Opportunities Amid Rising Oil Prices On April 12, Galaxy Securities released a report noting that March's Producer Price Index (PPI) turned positive year-on-year, driven by high oil prices and ongoing policy efforts. According to Jin10, the report emphasizes the potential for profit recovery in China's A-share market, particularly in upstream sectors. The report identifies several investment opportunities. Firstly, it suggests focusing on energy and alternative demand sectors, including coal, coal chemicals, new energy, shipping ports, and oil and gas. Additionally, there is potential for recovery in the non-ferrous metals sector, including precious and minor metals. Secondly, the report highlights defensive assets such as finance (banks), utilities, and transportation. Thirdly, it points to technology innovation and self-sufficiency sectors, including power equipment, energy storage, semiconductors, computing power, and communication equipment. In the consumer sector, it suggests focusing on agriculture, forestry, animal husbandry, fisheries, food and beverages, and household appliances. The report also notes that if there are signs of easing in ongoing conflicts, there could be significant recovery opportunities in previously oversold sectors. #GalaxySecurities#OilPrices#ProducerPriceIndex#ProfitRecovery#AShareMarket#UpstreamSectors#EnergySector#AlternativeDemand#Coal#NewEnergy#ShippingPorts#OilAndGas#NonFerrousMetals#PreciousMetals#DefensiveAssets#Finance#Utilities#Transportation#TechnologyInnovation#SelfSufficiency#PowerEquipment#EnergyStorage#Semiconductors#ComputingPower#CommunicationEquipment#ConsumerSector#Agriculture#FoodAndBeverages#HouseholdAppliances#RecoveryOpportunities