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

Резултати

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

Пребарај: #adventureawaits

当前筛选 #adventureawaits清除筛选
Auto Life

@revheadcrypto · Post #439 · 05.09.2024 г., 07:03

🚗✨Introducing the New Nissan Patrol & Armada!✨🚙 🌍 Available globally as the Patrol and in the USA as the Armada, these powerful SUVs are equipped with a robust 3.5L turbo V6 engine, delivering an impressive 425 HP and 700 Nm of torque! 💪🔧 (+7% power & +25% torque) paired with a smooth 9-speed automatic transmission. 📏 Built on the recently launched Infiniti QX80 platform, the Patrol has been slightly lengthened and widened while maintaining the same wheelbase. 🛠️ It now offers even more space for passengers, with an additional 145 mm in the third-row legroom, and a cargo capacity ranging from 578 to 2750 liters! 🧳📦 🌄 The all-wheel-drive system features a low range and optional rear differential lock for enhanced off-road capability. For the North American market, check out the rugged Armada Pro-4X variant, complete with air suspension, off-road bumpers, and all-terrain tires! 🌲🛤️ 💰 Prices have been announced only for the UAE, starting at approximately $65,000. Get ready for adventure with the new Nissan Patrol & Armada! 🚀🌟 #NissanPatrol#NissanArmada#SUV#OffRoad#AdventureAwaits#PowerfulPerformance#Auto

Auto Life

@revheadcrypto · Post #629 · 08.11.2024 г., 09:31

🚐✨Introducing the Luxurious Brabus Big Boy 1200 Motorhome!✨🚐 This stunning camper, priced at €1.26 million, measures an impressive 12 meters in length and is designed for a maximum of three residents. 🛏️👨‍👩‍👧 The Big Boy 1200 features several retractable modules that expand the living space during your stay, offering a spacious bedroom and a cozy living area that doubles as a dining room. 🛋️🍽️ In the bedroom, you'll find a full-size bed (160x200 cm), while an additional sleeping space for one person is cleverly located above the driver’s cabin. 💤🛌 Built on a robust three-axle Mercedes-Benz Actros chassis, this motorhome is powered by a 12.8-liter diesel engine that delivers an astonishing 530 hp and 2600 Nm of torque! 💪🚛 Get ready to travel in style and comfort! 🌍❤️ #Brabus#BigBoy1200#LuxuryMotorhome#VanLife#TravelInStyle#MercedesBenz#AdventureAwaits#Auto

Auto Life

@revheadcrypto · Post #569 · 11.10.2024 г., 06:43

🚗💨Introducing the Ford F-150 Raptor Shelby Baja Raptor!💥🔥 Get ready to unleash the power with an incredible 900-horsepower engine upgrade! 💪 The 3.5L V6 EcoBoost now roars at 550 hp, while the 5.2L V8 on the Raptor R delivers a staggering 730 hp with a new supercharger and custom exhaust! 🎉🔧 Key features include: ✨ Enhanced BDS suspension ✨ Massive 37-inch tires ✨ Custom hood with air intakes ✨ Heavy-duty bumpers and extra LED lights ✨ Robust cargo rack for the bed Starting at just $51,995 (excluding the base truck price), this beast is ready to dominate any terrain! 🌍🏞️ #FordF150#Raptor#ShelbyBajaRaptor#OffRoad#Power#TruckLife#AdventureAwaits#CarEnthusiast#Auto