Python中等值数和等值数之间的区别 [英] Difference between isnumeric and isdecimal in Python

查看:75
本文介绍了Python中等值数和等值数之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串的等值和十进制函数之间有什么区别( https://www.tutorialspoint.com/python3/python_strings.htm )?他们似乎给出了相同的结果:

What is the difference between isnumeric and isdecimal functions for strings ( https://www.tutorialspoint.com/python3/python_strings.htm )? They seem to give identical results:

>>> "123456".isnumeric()
True
>>> "123456".isdecimal()
True
>>> "123.456".isnumeric()
False
>>> "123.456".isdecimal()
False
>>> "abcd".isnumeric()
False
>>> "abcd".isdecimal()
False

我希望 isdecimal()对于"123.456"返回true,但不会.

I expected isdecimal() to return true for "123.456" but it does not.

推荐答案

这两种方法测试特定的Unicode字符类.如果字符串中的所有字符来自指定的字符类(具有特定的Unicode属性),则测试为true.

The two methods test for specific Unicode character classes. If all characters in the string are from the specified character class (have the specific Unicode property), the test is true.

isdecimal()不会测试字符串是否为十进制数字.请参见文档:

isdecimal() does not test if a string is a decimal number. See the documentation:

如果字符串中的所有字符均为十进制字符且至少包含一个字符,则返回true,否则返回false.小数字符是可用于以10为基数的数字的字符,例如U + 0660,阿拉伯文-印度数字零.正式的十进制字符是Unicode通用类别"Nd"中的字符.

Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category "Nd".

.句点字符不是 Nd 类别的成员;它不是十进制字符.

The . period character is not a member of the Nd category; it is not a decimal character.

str.isdecimal()字符是 str.isnumeric()的子集;这将测试所有数字字符.同样,从文档:

str.isdecimal() characters are a subset of str.isnumeric(); this tests for all numeric characters. Again, from the documentation:

如果字符串中的所有字符均为数字字符,并且至少包含一个字符,则返回true,否则返回false.数字字符包括数字字符,以及所有具有Unicode数值属性的字符,例如U + 2155,俗语分数五分之一.形式上,数字字符是具有属性值Numeric_Type = Digit,Numeric_Type = Decimal或Numeric_Type = Numeric的那些.

Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

Nd 在这里是 Numeric_Type = Digit .

如果要测试字符串是否为有效的十进制数字,只需尝试将其转换为浮点数即可:

If you want to test if a string is a valid decimal number, just try to convert it to a float:

def is_valid_decimal(s):
    try:
        float(s)
    except ValueError:
        return False
    else:
        return True

这篇关于Python中等值数和等值数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆