I'm trying to check if a string is numeric or not, using the isnumeric
function, but the results are not as expected. The function works only if it's a unicode string.
>>> a=u'1'
>>> a.isnumeric()
True
>>> a='1'
>>> a.isnumeric()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'isnumeric'
isnumeric
works only if its unicode. Any reason why?
Python isnumeric() method checks whether all the characters of the string are numeric characters or not. It returns True if all the characters are true, otherwise returns False. Numeric characters include digit characters and all the characters which have the Unicode numeric value property.
Here, isnumeric() checks if all characters in string are numeric or not.
The Python isnumeric method has a number of key differences between the Python isdigit method. While the isidigit method checks whether the string contains only digits, the isnumeric method checks whether all the characters are numeric.
A numeric character reference (NCR) is a common markup construct used in SGML and SGML-derived markup languages such as HTML and XML. It consists of a short sequence of characters that, in turn, represents a single character.
Just different name.
'1'.isdigit() True
Often you will want to check if a string in Python is a number. This happens all the time, for example with user input, fetching data from a database (which may return a string), or reading a file containing numbers. Depending on what type of number you are expecting, you can use several methods. Such as parsing the string, using regex, or simply attempting to cast (convert) it to a number and see what happens. Often you will also encounter non-ASCII numbers, encoded in Unicode. These may or may not be numbers. For example ๒, which is 2 in Thai. However © is simply the copyright symbol, and is obviously not a number.
link : http://pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With