TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #83 · 11 мај

У строки в 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

Hashtags

Резултати

Пронајдени 9 слични објави

Пребарај: #emiratos

当前筛选 #emiratos清除筛选
Communia

@communia · Post #37331 · 20.10.2023 г., 15:59

#PactoVerde. La #cop28 en #Emiratos pone en peligro de muerte a los trabajadores que están terminando la construcción de las instalaciones https://www.theguardian.com/environment/2023/oct/20/cop28-migrant-workers-uae-heat-climate-crisis

Communia

@communia · Post #37202 · 08.10.2023 г., 21:22

#Emiratos condena el ataque de #Hamas y llama al fin de la violencia en #Israel y #Gaza. https://www.haaretz.com/israel-news/2023-10-08/ty-article-live/over-250-israelis-killed-1-590-wounded-civilians-and-soldiers-held-hostage-in-gaza/0000018b-0cd2-d8fc-adff-6dfe855e0000#400069237

Communia

@communia · Post #37252 · 13.10.2023 г., 08:34

#España. ¿Cómo no va a reivindicar el #gas la burguesía española como si fuera lo mejor del #PactoVerde cuando sus principales aventuras son con el capital de #Qatar (lo que explica muchas cosas) y de #Emiratos y #ArabiaSaudí (lo que explica otras)? https://cincodias.elpais.com/opinion/2023-10-13/el-innegable-peso-del-gas-natural.html

Communia

@communia · Post #37567 · 10.11.2023 г., 10:56

#Clave. #Israel sustituye trabajadores de #Palestina por #migraciones temporales y precarias desde Asia, al estilo de #Emiratos, #Qatar o #ArabiaSaudí (aunque con condiciones relativamente mejores). El gran negocio conjunto de la burguesía #palestina e israelí deja de ser conjunto y la burguesía israelí pasa simplemente a buscar otro proveedor de trabajadores. Es decir, cierra la época del modelo bantustán para mantener lo esencial: la división de los trabajadores entre nativos y migrantes, y la posibilidad de deportar rápidamente en caso de conflicto. De momento llegarán 10.000 trabajadores desde #Ceilán. https://www.marianne.net/monde/proche-orient/sri-lanka-vietnam-israel-cherche-des-immigres-en-asie-pour-remplacer-les-palestiniens

Communia

@communia · Post #37044 · 11.09.2023 г., 22:41

#Marruecos y la ayuda post-terremoto «La renuencia de Marruecos a aceptar ayuda para el terremoto desconcierta a los gobiernos extranjeros» (léase EEUU) «un equipo de 50 personas de la Agencia de Ayuda Técnica de Alemania reunido en el aeropuerto de Colonia Bonn durante el fin de semana fue enviado a casa desde el aeropuerto el domingo después de que su oferta de ayuda no fuera aceptada.» «Países como #Francia, #Alemania, #Italia y #EEUU, junto con #ONU, dijeron que estaban esperando para brindar toda la ayuda posible después del devastador terremoto del viernes en las montañas del Alto Atlas. El Ministerio del Interior de Marruecos dijo en un comunicado el domingo que inicialmente aceptaría equipos de búsqueda y rescate sólo de #GranBretaña, #Qatar, #España y los #Emiratos Árabes Unidos (a los que llamó “países amigos”), después de tener en cuenta las “necesidades del país”.» https://www.washingtonpost.com/world/2023/09/11/morocco-earthquake-foreign-aid/

Communia

@communia · Post #37406 · 25.10.2023 г., 10:29

#Irán rearma a #Hamas mientras... https://www.wsj.com/world/middle-east/iran-weapons-west-bank-israel-war-8bf12d1f ... #EEUU manda a toda velocidad sistemas de defensa antiaérea a #Emiratos, #Kuwait, #Jordania, #Irak, #Qatar y #ArabiaSaudí pensando ya en una gran guerra de todo Oriente Medio con sus bases e intereses como objetivos primarios de los iraníes y sus aliados https://www.wsj.com/livecoverage/israel-hamas-war-news-gaza-palestinians/card/u-s-sends-air-defense-systems-to-gulf-countries-O11ZyqKBZhIjSprR7WoN

Communia

@communia · Post #37339 · 21.10.2023 г., 09:00

#Israel dice a sus ciudadanos que abandonen #Egipto y #Jordania lo antes posible y eviten #Marruecos, #Maldivas y #Emiratos en previsión de atentados y secuestros de la «jihad global» (= #HermanosMusulmanes / #Hamas bajo patrocinio de #Turquía y #Qatar + restos de #estadoislamico y #alqaeda) https://www.timesofisrael.com/israel-tells-citizens-to-leave-egypt-and-jordan-as-soon-as-possible-avoid-morocco/