I am trying to write a function which turns a string into an integer, with an exception to catch anything which is not a digit and return a SyntaxError. The try here should take a string and return an integer if all characters in the string are digits. An example value of (sti) would be 12a34.
def string2int(sti):
try:
int(float(sti))
if sti.isdigit():
return sti
except Exception, e:
raise SyntaxError('not an integer')
Trying to iron it out in a python visualizer gives me an attribute error on line 4: AttributeError: 'float' object has no attribute 'isdigit'
There is an all_digits function I can use that takes a string and returns True if all the characters of the string are digits and False otherwise, but I haven't been able to get the try to work using that either.
How can I write this so that if the string does represent a positive integer then that integer is returned?