Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't isnumeric working?

I was going through a very simple python3 guide to using string operations and then I ran into this weird error:

In [4]: # create string
        string = 'Let\'s test this.'

        # test to see if it is numeric
        string_isnumeric = string.isnumeric()

Out [4]: AttributeError                            Traceback (most recent call last)
         <ipython-input-4-859c9cefa0f0> in <module>()
                    3 
                    4 # test to see if it is numeric
              ----> 5 string_isnumeric = string.isnumeric()

         AttributeError: 'str' object has no attribute 'isnumeric'

The problem is that, as far as I can tell, str DOES have an attribute, isnumeric.

like image 569
Anton Avatar asked Apr 20 '14 14:04

Anton


People also ask

How do I use Isnumeric in Python?

The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the . are not.

Does Isnumeric work for strings?

Python String isnumeric() Method The str. isnumeric() checks whether all the characters of the string are numeric characters or not. It will return True if all characters are numeric and will return False even if one character is non-numeric.

What is the difference between Isdigit and Isnumeric 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.


3 Answers

No, str objects do not have an isnumeric method. isnumeric is only available for unicode objects. In other words:

>>> d = unicode('some string', 'utf-8') >>> d.isnumeric() False >>> d = unicode('42', 'utf-8') >>> d.isnumeric() True 
like image 180
Alexander Ejbekov Avatar answered Sep 25 '22 13:09

Alexander Ejbekov


isnumeric() only works on Unicode strings. To define a string as Unicode you could change your string definitions like so:

In [4]:         s = u'This is my string'          isnum = s.isnumeric() 

This will now store False.

Note: I also changed your variable name in case you imported the module string.

like image 31
theage Avatar answered Sep 22 '22 13:09

theage


One Liners:

unicode('200', 'utf-8').isnumeric() # True
unicode('unicorn121', 'utf-8').isnumeric() # False

Or

unicode('200').isnumeric() # True
unicode('unicorn121').isnumeric() # False
like image 42
nvd Avatar answered Sep 21 '22 13:09

nvd