All about Agile, Ansible, DevOps, Docker, EXIN, Git, ICT, Jenkins, Kubernetes, Puppet, Selenium, Python, etc
Difference between isnumeric and isdecimal in Python
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()
does not test if a string is a decimal number. See the documentation: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”.
The
.
period character is not a member of the Nd
category; it is not a decimal character.str.isdecimal()
characters are a subset of str.isnumeric()
; this tests for all numeric characters. Again, from the documentation: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
is Numeric_Type=Digit
here.
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
No comments:
Post a Comment
Thanks for your comments