Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
💰🇺🇸TECH WAGES HIT $178K MEDIAN AS AMERICA'S JOB MARKET SPLITS
🔹 Silicon Valley salaries surge to $178K average — up from $62K five years ago in dramatic wage explosion 📈
🔹 178,000 new positions added in March beating economists' 62,000 forecast by nearly triple margin 💼
🔹 Healthcare dominates hiring with 89,900 jobs while finance cuts 15,000 — clear sector winners emerging 🏥
🔹 Unemployment at 4.3% masks deeper issue: 322,000 more long-term jobless than year ago 📊
Two Americas emerging — tech prosperity vs persistent poverty 🤔💔
#WageGap#USEconomy
✨ More breaking stories coming soon 🚀
@america
📈US-China Trade Guardrails: Navigating Friction & Market Impact Mar-16-2026
Despite constructive talks between the US and China to establish trade 'guardrails,' friction persists with renewed Section 301 investigations. This delicate balance of managed tension rather than...
🔗Read Full Analysis
🎯 SPECIAL OFFER: 15% OFF
💸 Coupon Code: salenow15%
🚀 Upgrade to premium signals → https://markets.fxpremiere.com/en/signals?utm_source=telegram
📰 Stay ahead — get breaking financial news & analysis at https://markets.fxpremiere.com/en?utm_source=telegram
#USEconomy#ChinaEconomy#TradePolicy
🚨🇺🇸 IRAN CONFLICT'S SHADOW LOOMS OVER US ECONOMY
🔹 Oil prices jump: U.S. crude up 6.3% to $71.23, Brent 6.7% to $77.74/barrel 📈
🔹 Prolonged conflict could push oil past $100, gas to $3.50/gallon across US ⛽
🔹 Natural gas prices also rise, with Strait of Hormuz key for 20% of global supply ⚠️
🔹 Lingering inflation concerns exacerbated; Fed's target of 2% remains elusive at 3% 📉
🔹 Business confidence at risk, potentially slowing investment & hiring; 2025 hiring weakest since 2002 💔
Americans already sour on the economy – will regional conflicts push it to the brink? 🤔
#USEconomy#Inflation#Geopolitics
@america
U.S. job growth slows sharply in September
U.S. employment increased far less than expected in September amid a decline in government payrolls, but hiring could pick up in the months ahead as COVID-19 infections subside
#News#Reuters#Unemployment#USEconomy#LabourMarket
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
🇺🇸 U.S. Job Growth Slows in February Amid Economic Rebalancing!
🔹 After a robust January, U.S. job growth is expected to moderate in February, with economists projecting 60,000 new jobs—a significant slowdown from the start of the year 📉.
🔹 The unemployment rate is anticipated to hold steady at 4.3%, reflecting a more sustainable pace of hiring after 2025 saw the weakest payroll growth outside of a recession since 2003 📊.
🔹 January retail sales data, though impacted by severe winter weather, is forecast to show modest increases in key sectors, signaling cautious consumer spending after a period of heightened anxiety 🥶🛒.
🔹 Economists point to the late January/early February cold spell as a primary factor for the slowdown, particularly affecting weather-sensitive industries like construction and hospitality. However, the overall labor market conditions have stabilized since last fall 👷♀️🏨.
The economy is shifting gears – are we heading for a soft landing or bumpy ride? Tell us what YOU think! 🤔
#USEconomy#JobsReport#EconomicOutlook
@america
💪📈US ECONOMY DEFIES GEOPOLITICS WITH SURPRISING RESILIENCE AMID GLOBAL CHAOS
🔹 GDP growth accelerates to 2.2-2.4% in 2026 despite Middle East conflicts and energy price surges hitting global markets 🌍⛽
🔹 S&P 500 earnings projected to grow 16% while unemployment holds steady at 4.3% — corporate America staying strong 💼📊
🔹 AI-driven business investment up 4% as productivity gains fuel recovery from government shutdown impacts last quarter 🤖💻
While other nations crumble under geopolitical pressure, America's economy keeps powering through! That's economic supremacy 🇺🇸🔥💪
#USEconomy#EconomicGrowth#AmericanResilience
@america
💰🇺🇸FED PRIORITIZES INFLATION OVER JOBS AS ENERGY PRICES SURGE
🔹 March jobs report shows 178,000 payroll gains, unemployment steady at 4.3% 📊
🔹 Producer Price Index hits 3.4% core inflation, well above Fed's 2% target 📈
🔹 Iran war-driven energy costs creating stagflation risks for US economy ⛽
🔹 Only 6.9 million job openings — lowest since April 2020 pandemic lows 📉
🔹 Fed officials call inflation "orange to red" threat ahead of April 29 meeting 🚨
Cleveland Fed's Hammack warns tighter policy needed despite job market fragility 💪⚡
#USEconomy#FederalReserve#Inflation#JobsReport#Fed
@america
📉🇺🇸JOBS REPORT SHOCKER: 92,000 JOBS CUT
🔹 US employers slashed 92K jobs last month vs +50K gain expected by Wall Street 😱
🔹 Worst miss in years; unemployment ticks up to 4.3% as manufacturing sector bleeds 📈
🔹 GOP lawmakers suddenly silent as midterms loom; fears of economic sinkhole spreading 🤐
🔹 Chuck Schumer attacks: "Republicans are going to get wiped out" due to failed policies 🗣️
🔹 Retail & factory sectors leading the losses; "Trump Boom" narratives taking a massive hit 🏭
Republicans are panicking behind closed doors. Is the economy crashing right before voting day? 🤔
#Economy#JobsReport#Recession#Midterms#Politics#USEconomy
🚀 U.S. Economic Growth Projected to Remain Strong Despite War
The White House National Economic Council Director, Kevin Hassett, has stated that the U.S. economy is expected to maintain a growth rate of 4% to 5% this year, despite ongoing conflicts. According to Odaily, this optimistic outlook comes amid challenging global circumstances.
#USEconomy#EconomicGrowth#USMacro#GlobalConflict#EconomicOutlook
🚨📉BREAKING NEWS: 92,000 AMERICAN JOBS DISAPPEARED IN FEBRUARY
🔹 Catastrophic Jobs Report: The US economy shockingly lost 92,000 jobs last month, defying Wall Street's prediction of a +50k gain. An absolute disaster for the administration. 📉😱
🔹 Unemployment Surges: The jobless rate has officially ticked up to 4.3%, with the manufacturing and retail sectors bleeding the most positions across the nation. 🏭🇺🇸
This isn't just a blip. This is a five-alarm fire for the ruling party. Can they spin this before November? Doubtful. 🤔💸
#Economy#JobsReport#Recession#Midterms#Politics#USEconomy#Breaking
🚀 U.S. Inflation Rate Expectations for April Show Slight Increase
The initial estimate for the U.S. inflation rate expectations over a five to ten-year period in April was reported at 3.4%, according to Jin10. This figure slightly missed the anticipated rate of 3.5% but showed an increase from the previous value of 3.20%. The data reflects ongoing concerns about inflationary pressures in the U.S. economy.
#USInflation#InflationExpectations#Economy#USEconomy#InflationRate#Jin10
🚀 U.S. Consumer Spending Shows Minimal Growth Amid Inflation Concerns
U.S. consumer spending in February showed little growth, according to data from the U.S. Department of Commerce. This comes amid ongoing inflation concerns, which are expected to worsen due to the conflict involving Iran. According to Jin10, inflation-adjusted consumer spending increased by 0.1% compared to January. The core Personal Consumption Expenditures (PCE) index, excluding food and energy, rose by 0.4% from the previous month. The annual rate of the core PCE price index, favored by the Federal Reserve, recorded a 3.0% increase.
#ConsumerSpending#InflationConcerns#USEconomy#PCEIndex#IranConflict#FederalReserve#EconomicGrowth