Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
EU Scrutinizes Bing's Generative AI over Potential Election Risks
The European Commission is escalating its investigation into potential risks associated with generative AI features on Microsoft's Bing search engine. The Commission seeks information beyond what Microsoft previously provided.
The request stems from concerns that Bing might be violating the Digital Services Act. This act outlines risk assessments and mitigation measures for online platforms, particularly regarding "hallucinations" (false information generated by AI systems), deepfakes (manipulated media), and automated manipulation of services that could mislead voters.
The Commission emphasizes the potential threats posed by generative AI to civic discourse and electoral processes, particularly in the upcoming European Parliament elections.
Microsoft has until May 27th to comply with the legally binding request. Non-compliance could lead to significant fines of up to 1% of Microsoft's global turnover, or daily penalty payments calculated as a percentage of average daily income.
#DSA
🇦🇿 Ozarbayjonda Best Startup Project yarim final bosqichi bo‘lib o‘tdi!
“Digital Startup Awards” (DSA) butun mintaqa bo‘ylab eng iqtidorli startap asoschilarini birlashtirishda davom etmoqda. 🌟
Dunyo bo‘ylab kelib tushgan 350 dan ortiq ariza orasidan 20 ta ozarbayjonlik startap o‘z innovatsion g‘oyalarini taqdim etdi. Natijada ikki finalchi — “Starkids” va “Tryverse” — joriy yil dekabr oyida Toshkentda bo‘lib o‘tadigan Grand Final bosqichiga yo‘llanma oldi. 🚀
Jarayon tobora qizg‘in tus olmoqda — yakuniy bosqichga yaqinlashar ekanmiz, yangiliklarni kuzatishda davom eting!
📖To‘liq maqolani o'qing: startupbase.uz
—
🇦🇿Azerbaijan Hosts Its Best Startup Project Semifinal!
The Digital Startup Awards (DSA) continues to bring together the brightest founders from across the region. 🌟
Out of 350+ applications globally, 20 startups from Azerbaijan took the stage to pitch their innovative ideas — and two finalists, Starkids and Tryverse, have earned their spot in the Grand Final in Tashkent this December. 🚀
The momentum is growing — stay tuned as we move closer to the final showdown!
📖Read the full article here: startupbase.uz
#DSA#BestStartupProject#ITParkUzbekistan#AzerbaijanStartups#CentralAsiaStartups
🇦🇿 Ozarbayjonda Best Startup Project yarim final bosqichi bo‘lib o‘tdi!
“Digital Startup Awards” (DSA) butun mintaqa bo‘ylab eng iqtidorli startap asoschilarini birlashtirishda davom etmoqda. 🌟
Dunyo bo‘ylab kelib tushgan 350 dan ortiq ariza orasidan 20 ta ozarbayjonlik startap o‘z innovatsion g‘oyalarini taqdim etdi. Natijada ikki finalchi — “Starkids” va “Tryverse” — joriy yil dekabr oyida Toshkentda bo‘lib o‘tadigan Grand Final bosqichiga yo‘llanma oldi. 🚀
Jarayon tobora qizg‘in tus olmoqda — yakuniy bosqichga yaqinlashar ekanmiz, yangiliklarni kuzatishda davom eting!
📖To‘liq maqolani o'qing: startupbase.uz
—
🇦🇿Azerbaijan Hosts Its Best Startup Project Semifinal!
The Digital Startup Awards (DSA) continues to bring together the brightest founders from across the region. 🌟
Out of 350+ applications globally, 20 startups from Azerbaijan took the stage to pitch their innovative ideas — and two finalists, Starkids and Tryverse, have earned their spot in the Grand Final in Tashkent this December. 🚀
The momentum is growing — stay tuned as we move closer to the final showdown!
📖Read the full article here: startupbase.uz
#DSA#BestStartupProject#ITParkUzbekistan#AzerbaijanStartups#CentralAsiaStartups
🇲🇳 Mongoliyada Best Startup Project yarim final bosqichi boshlandi!
“Digital Startup Awards” (DSA) dasturi qizg‘in davom etmoqda — Mongoliya rasman o‘zining ilk “Best Startup Project” tanlovini o‘tkazib, eng yaxshi finalchilarni saralab oldi! 🚀
350 dan ortiq arizalar orasidan UWISH va EGUNE Mo‘g‘uliston yarim finalida g‘olib chiqdi va joriy yilning dekabr oyida Toshkentda bo‘lib o‘tadigan Grand finalda ishtirok etadi.
📖To‘liq maqolani o'qing: startupbase.uz
—
🇲🇳Mongolia Kicks Off the Best Startup Project Semifinals!
The Digital Startup Awards (DSA) program is in full swing — and Mongolia has officially hosted the first Best Startup Project competition, selecting its top finalists! 🚀
Out of 350+ applications, UWISH and EGUNE became the winners of the Mongolian semifinal and will compete in the Grand Final in Tashkent this December.
📖Read the full article here: startupbase.uz
#DSA#BestStartupProject#ITParkUzbekistan#StartupEcosystem#MongoliaStartups#Innovation#Entrepreneurship#CentralAsiaStartups
🚀 AI TRENDS | OpenAI to Be Regulated Under EU's Digital Services Act, Sources Say
OpenAI is set to be regulated under the European Union's Digital Services Act (DSA), according to sources cited by Handelsblatt. The company will be classified as a very large online search engine under the new regulations. According to Jin10, this classification will subject OpenAI to stricter compliance requirements aimed at ensuring transparency and accountability in its operations. The DSA is part of the EU's broader effort to regulate digital services and platforms, enhancing user protection and addressing issues such as misinformation and data privacy. OpenAI's inclusion under this regulatory framework highlights the growing scrutiny of AI technologies and their impact on society.
#AI#OpenAI#EU#DigitalServicesAct#DSA#Regulation#TechPolicy#DataPrivacy#Misinformation#Transparency#Accountability