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?
This question is related to
python
variables
python-2.7
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
Depending on your definition of shortly, you could use one of the following options:
try: int(your_input); except ValueError: # ...
your_input.isdigit()
parse
which is kind of the opposite of format
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
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.
Source: Stackoverflow.com