Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример).
Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать?
В Django по умолчанию есть готовая функция slugify для таких случаев.
Но я её никогда не использую. Почему? Потому что её недостаточно!
Приведём пример
>>> from django.utils.text import slugify
>>> slugify('This is a Title')
'this-is-a-title'
Пока всё отлично
>>> slugify('This is a "Title!"')
'this-is-a-title'
Спец символы удалились, всё хорошо.
>>> slugify('Это заголовок статьи')
''
Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить
>>> slugify('Это заголовок статьи', allow_unicode=True)
'это-заголовок-статьи'
Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте.
Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою.
Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку:
🔸1. Исходный текст:
>>> text = 'Мой заголовок №10 😁!'
Взял специально посложней со специальными символами.
🔸2. Транслит
Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги.
from unidecode import unidecode
>>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山")
'N S (r) u P 1/4 Yue Shan'
Очень крутая библиотека, советую👍
В нашем случае получаем такое преобразование:
>>> text = unidecode(text)
>>> print(text)
'Moi zagolovok No. 10 !'
Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы.
А еще наш код уже поддерживает любой язык, будь то хинди или корейский.
🔸4. Фильтр символов
Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона.
>>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text)
>>> print(text)
'Moi_zagolovok_No_10_'
Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_".
🔸5. Slugify
Осталось удалить лишние символы по краям и сделать нижний регистр
>>> text = text.strip('_').lower()
>>> print(text)
'moi_zagolovok_no_10'
Получаем отличный slug! 😎
🌎 Полный код в виде функции.
______________
PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию.
#libs#tricks#django
#Security vacuum fears grow amid reports of #ENDF withdrawals, alleged redeployment toward #Tigray Region
Withdrawal or reduced presence of federal forces in recent days is raising concerns among local communities. Residents in different parts of the country spoke to Addis Standard on their concern following federal forces evacuating their village while fueling speculation that troops are being redeployed northward amid rising tensions involving Tigray.
Residents in Dirashe district, Gardulla Zone, South Ethiopia Region, and Anfilo districts in Kellem Wollega Zone, Oromia Region, told Addis Standard that Ethiopian National Defense Forces (ENDF) have been vacating certain areas, creating security gaps and fueling local tensions. An AFP report confirmed similar reports of troop movements and heightened military tension near the Tigray border.
https://addisstandard.com/?p=55250
News: #Ethiopia, #Belarus sign military MoU ahead of Air Force’s 90th anniversary
Ethiopia and Belarus have signed a bilateral memorandum of understanding (MoU) aimed at strengthening military cooperation between the two countries, the Ethiopian National Defense Forces (#ENDF) said.
In a statement issued on 22 January 2026, the ENDF said the agreement was signed by Ethiopia’s Minister of Defense, Engineer Aisha Mohammed, and Pantus Dmitry Aleksandrovich, Minister of State Authority for Military Industry of the Republic of Belarus.
According to the statement, Aisha described the MoU as a significant step toward advancing Ethiopia’s military technology and industrial capacity, particularly as the country seeks greater self-sufficiency in defense production.
She also recalled previous agreements reached between the leaders of Ethiopia and Belarus, noting that those understandings provide the foundation for implementing the current strategic cooperation...
Read more: https://addisstandard.com/?p=54710
#ENDF Airborne School graduates combat paratroopers trained for #special_missions
Addis Abeba— The Ethiopian National Defense Force (ENDF) said its Airborne School, under the Special Operations Command Training Center, has today graduated combat paratroopers trained to carry out special missions.
Lieutenant General Shuma Abdeta, Commander of the Special Operations Command, attended the graduation ceremony and pinned “chest wings” on the graduates, according to a statement from ENDF.
Addressing the trainees, Lt. Gen. Shuma said the airborne force “is a cradle of great leaders and heroes,” describing it as a unit that “makes the country proud by concluding formidable and complex missions with victory.”
He added that joining the airborne force requires “exceptional bravery,” noting that a paratrooper must be “a determined hero, invincible to any earthly challenge, and capable of overcoming all obstacles to achieve success.”
https://www.facebook.com/share/1KTQkTwcNF/
News: #Tigray Interim Administration dismisses claims of #ENDF deployment, relocation to Northern Command camps
The Tigray Interim Administration has dismissed as “completely false” reports circulating in recent days alleging that the federal government ordered the #Ethiopian National Defense Forces (ENDF) to enter Tigray and that the regional administration had agreed to the relocation of federal troops to former Northern Command camps.
In a brief statement issued today, the Interim Administration described the claims as “misinformation and disinformation” intended to mislead the public and create unnecessary tension.
“There are rumors in recent days that the federal government has ordered the Ethiopian Defense Forces to enter Tigray, and the Tigray Interim Administration has agreed for the forces to settle in the former camps of #Northern Command,” the statement said.
“The source and the goal of this strategy of spreading such misinformation and....
Read more: https://addisstandard.com/?p=55289
News: Former minister #Gedu says #Eritrean, #Ethiopian forces operated “as a single force” until Pretoria ceasefire, disputes PM Abiy’s account of Asmara’s role in Tigray war
Former Minister of Foreign Affairs Gedu Andargachew has disputed Prime Minister Abiy Ahmed’s recent parliamentary account of Ethiopia’s wartime engagement with Eritrea, saying Eritrean forces fought alongside the Ethiopian National Defense Forces (#ENDF) “effectively as a single force” until the Pretoria ceasefire halted joint operations.
He said he proposed raising the withdrawal of Eritrean forces from Tigray during the visit but was instructed not to do so. According to Gedu, no message concerning the suffering of civilians in Tigray was delivered in Asmara.
In a letter dated 5 February 2026 and sent to Addis Standard, Gedu rejected Abiy’s claim that he served as the Prime Minister’s envoy to Eritrea after the outbreak of the war in Tigray to convey concerns over crimes ....
Read more: https://addisstandard.com/?p=55048
News: #US Assistant Secretary Christopher Landau, AFRICOM commander arrive in #Ethiopia, visit Air Force aviation expo
U.S. Assistant Secretary of State Christopher Landau arrived in Ethiopia today as part of a regional tour that includes #Egypt, Ethiopia, #Kenya, and #Djibouti, scheduled to run from 24 January to 1 February.
The Commander of the U.S. Africa Command (#AFRICOM), General Dagvin Anderson, is also in Ethiopia as part of the visit.
Today, Landau and General Anderson visited the International Aviation Expo organized by the Ethiopian Air Force, according to the Ethiopian National Defense Force (#ENDF). Field Marshal Birhanu Jula, Chief of General Staff of the Ethiopian National Defense Force, also took part in the visit.
The expo showcased aircraft, defense technologies, and related products from the Ethiopian Air Force, the Defense Engineering Industry Group,..
https://www.facebook.com/AddisstandardEng/posts/pfbid021qedgKswfSFzdABsQXmFSvjuiRtWQedXpLYXJysCdk1MBnWvdx4JZJTmEng9jPGRl