У строки в Python есть два очень похожих метода. На столько похожих что кажется они делают одно и тоже.
Это метод isdigit() и isnumeric()
Давайте посмотрим зачем нам два одинаковых метода? И так ли они одинаковы?
Очевидно что isdigit() говорит нам, состоит ли строка только из чисел 0-9
>>> '12'.isdigit()
True
>>> '12x'.isdigit()
False
>>> '-12'.isdigit()
False
>>> '12.5'.isdigit()
False
Можно предположить что isnumeric() делает более глубокий анализ и распознаёт в строке float или отрицательное число.
>>> '15'.isnumeric()
True
>>> '-15'.isnumeric()
False
>>> '15.2'.isnumeric()
False
Нет, всё так же как и с другим методом. В чем же тогда разница? Для начала посмотрим следующие примеры:
>>> '5'.isdigit(), '5'.isnumeric() # Обычная цифра 5
# True, True
>>> '꧕'.isdigit(), '꧕'.isnumeric() # Яванская 5
# True, True
>>> '෩'.isdigit(), '෩'.isnumeric() # Синхала 3
# True, True
>>> '৩'.isdigit(), '৩'.isnumeric() # Бенгальская 3
# True, True
>>> '༣'.isdigit(), '༣'.isnumeric() # Тибетская 3
# True, True
>>> '³'.isdigit(), '³'.isnumeric() # 3 верхний индекс (степень)
# True, True
>>> '𝟝'.isdigit(), '𝟝'.isnumeric() # Математическая двойная 5
# True, True
>>> '๔'.isdigit(), '๔'.isnumeric() # Тайская 4
# True, True
>>> '➑'.isdigit(), '➑'.isnumeric() # 8 в круге
# True, True
А теперь примеры в которых, по мнению Python, результаты не равны
>>> '¾'.isdigit(), '¾'.isnumeric() # дробь три четверти
# False, True
>>> '⅕'.isdigit(), '⅕'.isnumeric() # дробь одна пятая
# False, True
>>> '𒐶'.isdigit(), '𒐶'.isnumeric() # клинопись 3
# False, True
>>> '三'.isdigit(), '三'.isnumeric() # 3 из унифицированной идеограммы
# False, True
>>> '⑩'.isdigit(), '⑩'.isnumeric() # цифра 10 в круге
# False, True
>>> 'Ⅳ'.isdigit(), 'Ⅳ'.isnumeric() # Римская 4
# False, True
>>> '𑇪'.isdigit(), '𑇪'.isnumeric() # Сенегальская архаическая 10
# False, True
>>> '𐌢'.isdigit(), '𐌢'.isnumeric() # Этрусская цифра 10
# False, True
>>> 'ↂ'.isdigit(), 'ↂ'.isnumeric() # Римская цифра 10000
# False, True
>>> '〇'.isdigit(), '〇'.isnumeric() # Символ ККЯ ноль
# False, True
Получается, что isdigit() говорит нам, является ли символ десятичной цифрой или спецсимволом, имеющим цифирное значение после преобразования.
В свою очередь isnumeric() включает все дополнительные символы юникода которые имеют отношения к числовым и цифровым представлениям.
Ну и пара примеров в которых в обоих случаях символ не является числом, это эмодзи.
>>> '🕙'.isdigit(), '🕙'.isnumeric() # эмодзи 10 часов
# False, False
>>> '7️⃣'.isdigit(), '7️⃣'.isnumeric() # эмодзи 7
# False, False
Также есть еще один дополнительный и весьма полезный метод isdecimal().
Он нам сообщает, можно ли из указанного символа сделать простую десятичную цифру. То есть сработает ли метод int(x)
>>> '෩'.isdecimal(), int('෩') # Синхала 3
# True, 3
>>> '➑'.isdecimal(), int('➑') # 8 в круге
# False, ValueError
Какие выводы?
🔸 При определении цифры в строке isdigit() подходит лучше чем isnumeric(), но оба не гарантируют успешную конвертацию в int
🔸 Для однозначного определения возможности преобразования строки в int лучше подходит метод isdecimal()
🔸 Для однозначного определения символов 0...9 лучше использовать regex
Полный список символов юникода которые определяются как numeric
#basic
“When they attacked some village, they called all the people to one place. ‘Everyone must follow us and our religion. If not, we must shoot you,’” says Khuseini from Nigeria about Boko Haram terrorists.
This criminal group is responsible for killing thousands of people. Khuseini and his family fled their hometown when Boko Haram arrived. Now he lives in the Dar es Salaam refugee camp and teaches Arabic to kids at the local school. Khuseini says the kids are deeply traumatised by the terrorists’ brutality. They remember how Boko Haram attacked their town, killing their friends. There are machine guns, blood, and killings even in kids’ drawings.
Today is Children’s Day in Nigeria. Watch the clip to see how kids – Boko Haram’s victims - live in the refugee camp and try to get back to everyday life. Then, find out more in our documentary Hot Spot Chad.
#crime
Follow: https://t.me/rtdocumentary
‘He’s not resisting arrest; he’s on the ground. You’ve him in handcuffs. Why is there a need to hit him in the back with a rifle?’ – asks a desperate mother whose child died due to police brutality. Quincy and his girlfriend argued, he left the house, leaving her angry. She called the police and told them he had a rifle. That fatal lie cost Quincy his life. Five police officers didn’t even intend to find out the truth but tackled and beat the young man to death.
Cases like this are common in the USA. Hundreds of people die every year at the hands of law enforcement officers. Watch the clip to see some cases. Do you think it’s possible to change the situation? See the documentary Once Upon A Crime to learn what people do to stop police brutality.
#crime
Follow: https://t.me/rtdocumentary
🎬 Adolescence
Gênero: #Crime, #Drama
⭐️ IMDb: 8.1
⏳ Duração: 15 Episódios
📝 Sinopse:
Quando um garoto de 13 anos é acusado do assassinato de um colega de classe, sua família, o terapeuta e o detetive responsável ficam perguntando o que realmente aconteceu.
Fonte: IMDb
🔵Inscreva-se em @Assistir
*Patrocinado: Anime Bot
🍿 'The Penguin': The Most Anticipated Spin-off of 'The Batman' 🎬
📆Premiere: September 19, 2024
🎭Genre: #Crime · #Drama
Colin Farrell dives into the role of Oz Cobb, aka The Penguin, in this series that promises to expand the universe of Matt Reeves' 'The Batman.' With 3.5 hours of daily makeup, Farrell transforms into Gotham's crime boss. The trailer, unveiled at Comic-Con, left everyone in awe. 🎥
The interesting part is how Reeves initially planned a series for DC, and HBO finally made it happen. Cristin Milioti and Rhenzy Feliz join Farrell in an impressive cast. And watch out! The Penguin will return in 'The Batman II' in 2026. 🦇✨
🍿The Penguin: Colin Farrell Returns to Gotham
📆Release: Fall 2024
🎭Genre: #Crime · #Drama
The new trailer for 'The Penguin' brings Colin Farrell back as Gotham's infamous gangster, Oswald Cobblepot. This spin-off from Matt Reeves' 'The Batman' follows Cobblepot's rise to power after the death of Carmine Falcone. 🚦🔫
What's really fascinating is how Farrell's makeup has evolved, giving him an even more menacing look true to the iconic DC villain. Plus, the brewing tension with Sofia Falcone, played by Cristin Milioti, promises electrifying drama. Don't miss this thriller, which is already shaping up to be a hit. 🌆🔥
> 𝘴𝘦𝘳𝘪𝘦𝘴 · 🚀𝘣𝘰𝘰𝘴𝘵