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!

6
  • 4
    What Python version are you using? Commented Mar 7, 2019 at 9:28
  • 3
    you are trying in python version 2 so this error Commented Mar 7, 2019 at 9:28
  • 3
    Don't read the python 3 docs if you're using python 2. Commented Mar 7, 2019 at 9:28
  • 3
    You could use isdigit(), if that helps. It's not exactly the same, but it's available in Python 2. Commented Mar 7, 2019 at 9:29
  • 1
    Possible duplicate of 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. Commented Mar 7, 2019 at 9:33

4 Answers 4

4

replace isnumeric() with isdigit() as

s = str(10)
if s.isdigit():
    print s
Sign up to request clarification or add additional context in comments.

1 Comment

@meowgoesthedog solution was specific to above example, where number is integer
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)

Comments

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")

Comments

1

Try using replace with isdigit:

print(s.replace('.', '').isdigit())

2 Comments

Wow... that was clean !
@programmer Lol, happy it's good

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.