Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python isnumeric function works only on unicode

Tags:

python

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?

like image 492
user1050619 Avatar asked May 31 '13 18:05

user1050619


People also ask

How does Isnumeric work in Python?

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.

Does Isnumeric work on strings?

Here, isnumeric() checks if all characters in string are numeric or not.

What is the difference between Isnumeric and Isdigit in Python?

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.

What is an Isnumeric character?

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.


2 Answers

Just different name.

'1'.isdigit() True

like image 195
Artem Volkhin Avatar answered Sep 20 '22 17:09

Artem Volkhin


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/

like image 41
maazza Avatar answered Sep 21 '22 17:09

maazza