0

Can someone kindly explain why the following throws an exception? And what should I do with variable s to find out whether it contains a number?

s = str(10)
if s.isnumeric():
    print s

When I read Python documentation it seems to me the above should work. See:

https://docs.python.org/3/library/stdtypes.html?highlight=isnumeric#str.isnumeric

But what I get is:

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

Any help is most appreciated.

Thank you!

Nexaspx
  • 371
  • 4
  • 20
MMazzon
  • 364
  • 1
  • 2
  • 15
  • 4
    What Python version are you using? – deceze Mar 07 '19 at 09:28
  • 3
    you are trying in python version 2 so this error – ravishankar chavare Mar 07 '19 at 09:28
  • 3
    Don't read the python 3 docs if you're using python 2. – Aran-Fey Mar 07 '19 at 09:28
  • 3
    You could use [`isdigit()`](https://docs.python.org/2/library/stdtypes.html?highlight=isdigit#str.isdigit), if that helps. It's not exactly the same, but it's available in Python 2. – khelwood Mar 07 '19 at 09:29
  • 1
    Possible duplicate of [AttributeError: 'str' object has no attribute 'isnumeric'](https://stackoverflow.com/questions/49263568/attributeerror-str-object-has-no-attribute-isnumeric). It would be beneficial if you gave more information about your problem, like the python version you're using. – Nexaspx Mar 07 '19 at 09:33
  • Thanks everyone! I was using Python inside Google's appengine, and that turns out to be version 2.7 – MMazzon Mar 07 '19 at 09:42

4 Answers4

4

replace isnumeric() with isdigit() as

s = str(10)
if s.isdigit():
    print s
programmer
  • 411
  • 4
  • 10
2

for python 2 isdigit() and for python 3 isnumeric()

python 2

s = str(10)
if s.isdigit():
    print s

python 3

 s = str(10)
 if s.isnumeric():
    print(s)
bkawan
  • 1,171
  • 8
  • 14
1

You are obviously using python 2, so a such method does not exist.

That said, the most pythonic way would be to try to convert it

try:
    print(float(s))  # or int(s)
except ValueError:
    print("s must be numeric")
blue_note
  • 27,712
  • 9
  • 72
  • 90
1

Try using replace with isdigit:

print(s.replace('.', '').isdigit())
U13-Forward
  • 69,221
  • 14
  • 89
  • 114