[Python Wpg] String to integer conversion

Jason Hildebrand jason at peaceworks.ca
Tue Mar 28 17:59:28 EST 2006


On Tue, 2006-03-28 at 16:50 -0600, Mike Pfaiffer wrote:
> As the title suggests I want to convert a string to an 
> integer. I can use the atoi or int functions. These work well if the contents 
> of the string is an actual integer. If someone decides to say... put their 
> name in the string (through a raw_input function) then the function crashes. 
> Is there a simple way to check if the value of the string is numeric first or 
> better yet return zero if the value of the string contains alphabetic 
> characters?

Hi Mike,

Just try to convert the input, and catch the exception if necessary,
defaulting to 0:

s = raw_input()
try:
    i = int(s)
except ValueError:
    i = 0

-- 
Jason D. Hildebrand
T: 204 775 1212
E: jason at peaceworks.ca





More information about the Winnipeg mailing list