Заметка начинающим, которые часто сталкиваются с подобной непоняткой.
Ситуация следующая, есть список файлов:
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
Raqamli texnologiyalar va sun’iy intellektni rivojlantirish ilmiy tadqiqot instituti bilan hamkorlik masalalari muhokama etildi.
🇺🇿 UZB
Обсуждены вопросы развития сотрудничества с Научно-исследовательским институтом развития цифровых технологий и искусственного интеллекта.
🇷🇺 RU
Discussions on the development of cooperation with the Digital Technologies and Artificial Intelligence Research Institute have taken place.
🇬🇧 ENG
#GraduateSchool#DigitalAI#Collaboration#AIDevelopment
Web-site | Telegram | Facebook | Instagram
NIST Releases Tool for Testing AI Model Risks
The National Institute of Standards and Technology (NIST) has re-released Dioptra, a modular, open-source tool designed to assess and mitigate risks associated with AI models. Originally launched in 2022, Dioptra focuses on evaluating how malicious attacks, especially those that "poison" AI training data, can degrade an AI system's performance. This tool is crucial for companies training AI models and provides a common platform for simulating threats and conducting "red-teaming" exercises.
NIST's initiative, supported by President Joe Biden’s executive order on AI, aims to help government agencies, small to medium-sized businesses, and the broader community assess AI developers' claims and enhance AI safety standards. Dioptra's release aligns with global efforts, such as the U.K.'s AI Safety Institute’s Inspect tool, to advance AI model testing and ensure responsible AI development.
While Dioptra offers significant benefits, it currently works only with models that can be downloaded and used locally, excluding those gated behind APIs like OpenAI’s GPT-4. Despite this limitation, Dioptra represents a vital step towards understanding and mitigating AI risks, promoting a safer AI ecosystem.
#AI#AIDevelopment#AISafety#NIST#Cybersecurity
Introducing the Frontier Model Forum: Advancing Safe AI Development
Hey AI enthusiasts! Four major players in the AI industry, including Google, Microsoft, OpenAI, and Anthropic, have come together to form the Frontier Model Forum.
The primary goal of this industry body is to ensure the safe and responsible development of advanced AI models that go beyond the capabilities of current technologies.
Brad Smith, President of Microsoft, emphasized the importance of taking responsibility in developing AI technology, making sure it remains secure, safe, and under human control.
The Frontier Model Forum has outlined key objectives, including promoting AI safety research, encouraging responsible AI model deployment, discussing trust and safety concerns with policymakers and academics, and leveraging AI for societal benefits, such as addressing climate change and detecting cancer.
#AIandLaw#AIdevelopment#FrontierModelForum#AIRegulation#TechNews
G7 Leaders Agree on International Guiding Principles for AI Development
Hello, everybody! The G7 leaders have reached a consensus on International Guiding Principles and a voluntary Code of Conduct for AI developers under the Hiroshima AI process.
The intention is to harmonize international standards with EU regulations to ensure the responsible and trustworthy development of AI.
The eleven principles provide a roadmap for the responsible advancement, deployment, and utilization of advanced AI systems, including foundation models and generative AI.
These principles encompass commitments to address risks, prevent misuse, promote responsible information sharing, mandate incident reporting, bolster cybersecurity measures, and introduce a labeling system for AI-generated content.
#G7Leaders#AI#AIStandards#EURegulations#AIAct#AIDevelopment
🚀 AI TRENDS | OpenAI Plans Phased Rollout of New Model
OpenAI is preparing to introduce a new model in a phased manner, according to Axios. The company aims to ensure a smooth deployment by gradually releasing the model, allowing for adjustments based on initial feedback and performance. This approach is intended to optimize the model's integration and effectiveness across various applications. OpenAI's strategy reflects its commitment to maintaining high standards in AI development and deployment.
#OpenAI#AI#AITrends#ModelDeployment#TechNews#Innovation#AIdevelopment
🚀 Tether CEO Advocates for Open AI Development
Tether CEO Paolo Ardoino has expressed his views on the development of artificial intelligence, stating that AI should be as open as freedom. According to Odaily, Ardoino criticized the centralized approach to AI development, describing it as a 'dead end.' In contrast to the closed AI systems being developed by major tech companies, Tether is exploring alternative methods through QVAC, which focuses on running AI models on local devices. This approach aims to give users control over their data and computing power, aligning with the crypto industry's core principle of self-custody, where users maintain autonomy over their data and computational resources.
#Tether#CEO#AIdevelopment#openAI#freedom#centralizedAI#selfcustody#crypto#localdevices#dataprivacy
🚀 AI TRENDS | OpenAI's Sam Altman Addresses AI Development Concerns and Recent Incident
OpenAI founder Sam Altman has expressed understanding of societal fears regarding the rapid development of artificial intelligence. According to Odaily, Altman acknowledged that the current period is marked by significant technological change, with associated risks escalating to systemic challenges at the societal level. He emphasized that AI power should not be concentrated in a few institutions and advocated for broader distribution through technological democratization and institutional constraints.
Addressing a recent incident where his residence was targeted with a Molotov cocktail, Altman admitted to underestimating the impact of public narratives and emotions amid AI-related anxieties. He also acknowledged mistakes in company governance and conflict management, offering apologies for past actions. Furthermore, Altman reiterated his decision to reject Elon Musk's attempts to control OpenAI, ensuring the company's independent development.
Previously, it was reported that the OpenAI founder's residence was attacked with a Molotov cocktail.
#AI#OpenAI#SamAltman#AIdevelopment#technologicalchange#AIsociety#democratization#institutionalconstraints#Molotovcocktail#publicnarratives#conflictmanagement#ElonMusk#companygovernance#independence