[Tutor] Convert String to Int

spir denis.spir at free.fr
Mon Jan 19 09:43:50 CET 2009


Le Sun, 18 Jan 2009 21:59:04 -0500,
bob gailer <bgailer at gmail.com> a écrit :

> Ian Egland wrote:
> > 'Allo All.
> >
> > I know that, should you want to get an int from the user, you use 
> > int(input("Question!")). However, what if the user wasn't that savvy 
> > and didn't realize he/she HAD to enter a number? Program crash. Is 
> > there a way that I can get the input as a string, check and see if 
> > it's convertible to an integer, convert it if it is and ask them to 
> > try again if it's not?
> 
> a = raw_input("Enter an integer:")
> if a.isdigit():
>   # process input
> else:
>   # complain
> 
 
Actually, you probably run python 3.0, as you first wrote:

int(input("Question!"))

Before py3.0, input() would have processed & converted automatically the user input text (type string) into a number, if possible. So that int() would be useless. Try:

>>> type(input())
1
<type 'int'>

If you get this output, you have py<3.0 installed. But this behaviour was not the best (both for stability and security reasons) so that it was recommanded to use raw_input() instead, that keeps the input as raw string and lets the programmer process it carefully according to actual needs.
With python 3, only raw_input() remains, but it has been renamed to "input()", so that only the correct feature is available.
 
denis

------
la vida e estranya


More information about the Tutor mailing list