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

Резултати

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

Пребарај: #goldholdings

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

@CryptoM · Post #65092 · 11.04.2026 г., 00:24

🚀 PRECIOUS METALS | SPDR Gold Trust Holdings Remain Unchanged at 1,052.419 Tons The SPDR Gold Trust, recognized as the world's largest gold ETF, reported no change in its holdings, maintaining a total of 1,052.419 tons. According to Jin10, this stability in holdings comes amid fluctuating market conditions and investor sentiment. The unchanged status reflects the current market dynamics and investor strategies in the precious metals sector. #preciousmetals#SPDRGoldTrust#goldETF#marketdynamics#investorsentiment#goldholdings

Crypto M - Crypto News

@CryptoM · Post #65398 · 13.04.2026 г., 05:07

🚀 PRECIOUS METALS | UBP Increases Gold Holdings, Forecasts Year-End Price to Reach $6,000 Union Bancaire Privée (UBP) has increased its gold holdings, projecting that the price of gold will reach $6,000 by the end of the year. According to Jin10, the bank's decision to bolster its gold reserves reflects a strategic move in response to anticipated market conditions. UBP's forecast suggests a significant rise in gold prices, driven by factors such as global economic uncertainties and inflationary pressures. The bank's outlook aligns with broader market sentiment, where investors are increasingly turning to precious metals as a hedge against volatility. This move by UBP underscores the growing importance of gold in investment portfolios amid fluctuating financial markets. #preciousmetals#gold#UBP#investment#inflation#economicuncertainty#goldholdings#marketforecast#financialmarkets#hedge

Crypto M - Crypto News

@CryptoM · Post #64780 · 09.04.2026 г., 22:29

🚀 PRECIOUS METALS | SPDR Gold Trust Reduces Holdings by 0.571 Tons The world's largest gold ETF, SPDR Gold Trust, has decreased its holdings by 0.571 tons, bringing the current total to 1,052.419 tons. According to Jin10, this adjustment reflects ongoing market dynamics and investor sentiment towards gold. The reduction in holdings may indicate a shift in investment strategies or responses to recent economic developments. SPDR Gold Trust's holdings are closely watched as a barometer for global gold demand and investment trends. #preciousmetals#SPDRGoldTrust#goldETF#goldholdings#investmentstrategies#economicdevelopments#globalgolddemand#goldmarket

Crypto M - Crypto News

@CryptoM · Post #64663 · 09.04.2026 г., 13:13

🚀 PRECIOUS METALS | Poland's Central Bank Holds 580 Tons of Gold Poland's Central Bank Governor, Adam Glapiński, has announced that the central bank currently holds 580 tons of gold. According to Jin10, this substantial reserve underscores Poland's strategic approach to strengthening its financial security and diversifying its assets. The gold holdings are part of a broader effort to ensure economic stability and safeguard against global market fluctuations. Poland's commitment to maintaining a robust gold reserve reflects its proactive measures in navigating the complexities of the international financial landscape. #Poland#CentralBank#GoldReserves#FinancialSecurity#EconomicStability#GlobalMarket#AssetDiversification#GoldHoldings#InternationalFinance