Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
MGNREGS demand falls to 17.5M in Apr 2026 vs 27.2M YoY (-36%). Participation was 18.4M in Mar 2026; trend shows 11–36% YoY declines since Jul 2025. March IIP grew 4.1% (manufacturing 4.3%, mining 5.5%), indicating shift to farm/industrial work. #Jobs
CTO (Texnik Direktor) kerak
ConnectaCRM asoschisi Ziyobek yangi startap uchun texnik direktor qidirmoqda. Startap hali yosh, biroq allaqachon to’lov qilayotgan mijozlarga ega. Yangi CTO mahsulotni rivojlantirish, texnik infratuzilmani qurish, sun’iy intellektni integratsiya qilish va texnik jamoani shakllantirishda Ziyobekka hamkor bo’ladi.
Texnik stek: Python/Django, TypeScript/React.
Oylikdan ($2000+) tashqari startapdan ulush ham beriladi. Yosh startapni rivojlantirish va startap bilan birga o’sish uchun yaxshi imkoniyat.
Qisqacha intro va rezyume bu yerga yuboriladi: [email protected]
P.S.: Bu xabar reklama emas. Ziyobekni shaxsan taniyman va startaplarga yordam berish juda yaxshi ish.
Ziyobekdan: Qo’shimcha takliflar bo’lsa interviewda kelishamiz.
@farhodjon#jobs
#jobs
I vaguely feel there's a talent shortage in Germany. "Hiring is hard". I heard this several times. Our team also need more hires.
So the company came up with this: Land a job at Zalando within 3 days after the final interviews!
https://jobs.zalando.com/en/jobs/4004181/?gh_src=%20f46af3281us
📊🇺🇸U.S. JOBS REPORT: $115K ADDED IN APRIL — CRUSHES $70K FORECAST
🔹 Nonfarm payrolls surge $115K vs $70K expected — biggest beat in 6 months 📈
🔹 March numbers revised UP from $178K to $185K — labor momentum building 💪
🔹 Unemployment holds at 3.9% while participation rate climbs to 62.7% — more Americans entering workforce 🎯
🔹 Wage growth moderates to 3.9% annually from 4.1% — Fed's inflation fight working 💰
Wall Street cheering but Fed still cautious on rate cuts — September decision now in focus 🔥👀
#USNews#jobs
✨ More breaking stories coming soon 🚀
🛡️ Informed readers make better decisions 💪
@america
📊🇺🇸US JOBS MARKET BOUNCES BACK — $178K ADDED IN MARCH, UNEMPLOYMENT DROPS TO 4.3%
🔹 March payrolls crushed Wall Street forecasts by $118K — economists predicted $60K, got robust $178K positions 💪
🔹 Unemployment rate falls to 4.3% from 4.4%, driven by fewer job separations and 332K fewer unemployed Americans 📉
🔹 Healthcare leads hiring surge with $76K-$89K new jobs, construction adds $26K as manufacturing beats forecasts 🏗️
🔹 Private sector powered growth with $186K additions while government shed 8K positions — clear recovery signal 📈
After February's brutal -$133K loss, this reversal proves America's job machine isn't broken yet! 🚀💼
#USNews#jobs
@america
After years of struggling to find enough workers for some of the nation’s toughest lockups, the Federal Bureau of Prisons is facing a new challenge: Corrections officers are jumping ship for more lucrative jobs at Immigration and Customs Enforcement.
This is one of the unintended consequences of the Trump administration’s focus on mass deportations. For months, ICE has been on a recruiting blitz, offering $50,000 starting bonuses and tuition reimbursement at an agency that has long offered better pay than the federal prison system. For many corrections officers, it’s been an easy sell.
Workers at detention centers and maximum-security prisons from Florida to Minnesota to California counted off the number of co-workers who’d left for ICE or were in the process of doing so. Six at one lockup in Texas, eight at another. More than a dozen at one California facility, and over four dozen at a larger one. After retirements and other attrition, by the start of November the agency had lost at least 1,400 more staff this year than it had hired, according to internal prison data shared with ProPublica.
“We’re broken and we’re being poached by ICE,” one official with the prison workers union told ProPublica. “It’s unbelievable. People are leaving in droves.”
#ICE#Jobs
👂More on Trump's Ear
На всякий случай напоминаю что помимо того что я тут веду канал и пишу на всякие разные темы, я ещё и являюсь директором Инфокультуры (@infoculture).
У нас в Информационой культуре идёт много проектов и прямо сейчас мы расширяем команду. Нужны разработчики и аналитик по работе с данными. Все проекты которые мы делаем, или про общественную пользу, или сами по себе общественной пользой являются.
Вот тут можно увидеть вакансии подробно - https://moikrug.ru/companies/infoculture а вопросы задавать мне в личке в телеграм https://t.me/ibegtin или на почту [email protected]
#jobs#data
📈🇺🇸US JOBS MARKET TAKES DEVASTATING HIT
🔹 Unemployment rate climbs to 4.4% in February, up from 4.3% in January 📊
🔹 Economy LOSES 92,000 jobs as total employment drops by 185,000 💔
🔹 Unemployed Americans increase by 203,000 to 7.57 million people 😰
🔹 Youth unemployment spikes to 9.5%, long-term joblessness rises to 1.11% 📉
🔹 Labor participation falls to 62.0% as workers drop out of job hunt 🚪
Construction sector hit hardest with 6.3% unemployment rate 🏗️❌
Expected to reach 4.5% by Q1 end — approaching November's 4-year high 🚨
Iran war costs + economic uncertainty crushing American workers 💸⚔️
#USNews#economy#jobs
@america
More than 1.2 million immigrants disappeared from the labor force from January through the end of July, according to preliminary Census Bureau data analyzed by the Pew Research Center. That includes people who are in the country illegally as well as legal residents.
Immigrants make up almost 20% of the U.S. workforce and that data shows 45% of workers in farming, fishing and forestry are immigrants, according to Pew senior researcher Stephanie Kramer. About 30% of all construction workers are immigrants and 24% of service workers are immigrants, she added.
#Trump#migrants#jobs
👂More on Trump's Ear ⚠️