24
votes

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.

4
Not in Python 2, change that string to a unicode string. - Ashwini Chaudhary
Try using isdigit instead. - sshashank124
Found the answer: The text is unicode in Py3 by default. stackoverflow.com/questions/16863696/… - Anton
Post that as an answer with explanation. Accept it. Question resolved. - sshashank124

4 Answers

21
votes

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
5
votes

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.

5
votes

One Liners:

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

Or

unicode('200').isnumeric() # True
unicode('unicorn121').isnumeric() # False
2
votes

if using python 3 wrap string around str as shown below

str('hello').isnumeric()

This way it behaving as expected