45

For example, I want to check a string and if it is not convertible to integer(with int()), how can I detect that?

5
  • There is already a solution here stackoverflow.com/questions/354038/… Commented Sep 17, 2012 at 19:44
  • For clarity, should '-99' be allowed? What about '+123'? Or " 1729 " (integer with leading and trailing spaces). '0x123'? Commented Sep 17, 2012 at 19:52
  • @MarkDickinson -- why wouldn't '-99' be allowed? Commented Sep 17, 2012 at 19:57
  • 1
    @mgilson: No idea---I can't guess what the OP's usecase is. But it's an obvious example that isn't served so well by the 'isdigit' answer. Commented Sep 17, 2012 at 19:59
  • See also: stackoverflow.com/questions/379906/… Commented Jul 21, 2022 at 23:21

2 Answers 2

49

Use the .isdigit() method:

>>> '123'.isdigit()
True
>>> '1a23'.isdigit()
False

Quoting the documentation:

Return true if all characters in the string are digits and there is at least one character, false otherwise.

For unicode strings or Python 3 strings, you'll need to use a more precise definition and use the unicode.isdecimal() / str.isdecimal() instead; not all Unicode digits are interpretable as decimal numbers. U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example.

Sign up to request clarification or add additional context in comments.

4 Comments

-1 for a="0x12" a.isdigit()` >>>False
I didn't downvote, but " 1234".isdigit() will return False even though int will happily ignore the space in the front.
@user1655481: that's not a number either, it's a python hex literal. int('0x12') throws ValueError unless you specify a base.
@mgilson: that's kind of the point of the function. It depends on your usecases as to what you need, if .strip() is needed, etc.
33

You can always try it:

try:
   a = int(yourstring)
except ValueError:
   print "can't convert"

Note that this method outshines isdigit if you want to know if you can convert a string to a floating point number using float

1 Comment

Upvote. It's more pythonic to just try..except :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.