54

I have an application that has a couple of commands. When you type a certain command, you have to type in additional info about something/someone. Now that info has to be strictly an integer or a string, depending on the situation.

However, whatever you type into Python using raw_input() actually is a string, no matter what, so more specifically, how would I shortly and without try...except see if a variable is made of digits or characters?

6
  • 4
    You could do: "0".isdigit(). Documentation: docs.python.org/2/library/stdtypes.html#str.isdigit Commented May 10, 2013 at 18:08
  • 1
    Checking an object's type in Python is a bad idea - it makes Python's dynamic nature less useful. It's easier to ask for forgiveness than permission. Commented May 10, 2013 at 18:15
  • 1
    Why the aversion to try..except here? This is exactly what you'd use exception handling for. Commented May 10, 2013 at 18:23
  • 1
    Mostly because I don't understand try...except... Commented May 10, 2013 at 19:57
  • isinstance (in answer below) is a good way to go in the case of just needing to know whether the content of a variable is a string or integer. This can happen when a user option can be either. Commented Mar 21, 2017 at 7:56

5 Answers 5

103

In my opinion you have two options:

  • Just try to convert it to an int, but catch the exception:

    try:
        value = int(value)
    except ValueError:
        pass  # it was a string, not an int.
    

    This is the Ask Forgiveness approach.

  • Explicitly test if there are only digits in the string:

    value.isdigit()
    

    str.isdigit() returns True only if all characters in the string are digits (0-9).

    The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).

    This is often called the Ask Permission approach, or Look Before You Leap.

The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.

If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.

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

8 Comments

The are other options. Better say that those two options are just what you would recommend yourself.
@android: The other options are overkill for most situations. Yet, quantified it.
The problem is that I don't really understand try...except, so if you could explain it more thoroughly, that would be great.
@user2154354: Operations can throw exceptions; these cut through the normal flow of code, they 'fall down' through the stack; functions immediately return, until something 'catches' the exception. The try:..except: statement does the catching. int() can throw a ValueError exception, but we specifically catch it again to detect that the string was not convertable to an integer. See the Python tutorial for more details.
@Veedrac: indeed, pointed out now.
|
41

if you want to check what it is:

>>>isinstance(1,str)
False
>>>isinstance('stuff',str)
True
>>>isinstance(1,int)
True
>>>isinstance('stuff',int)
False

if you want to get ints from raw_input

>>>x=raw_input('enter thing:')
enter thing: 3
>>>try: x = int(x)
   except: pass

>>>isinstance(x,int)
True

3 Comments

Use basestring instead of str, to catch unicode, see stackoverflow.com/questions/1979004/…
That's perfect for me, it works for positive and negative numbers ... cool, thanks
one liner: print(isinstance('stuff',int))
8

The isdigit method of the str type returns True iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.

1 Comment

isdigit() retunrs False for negative numbers
2

Depending on your definition of shortly, you could use one of the following options:

Comments

1

Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.

intresult = None
while intresult is None:
    input = raw_input()
    try: intresult = int(input)
    except ValueError: pass

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.