Question

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?

Was it helpful?

Solution

def string2int(sti):
    try:
        return int(sti)
    except ValueError:
        raise SyntaxError('not an integer')

Or:

def string2int(sti):
    if sti.isdigit():
        return int(sti)
    else:
        raise SyntaxError('not an integer')

OTHER TIPS

In your function if sti is an integer, this should simply work, but just for regular integers like 123 not even "+1" or "1e2":

def string2int(sti):
    try:
        if sti.isdigit():
            return sti

So you can use regular expressions:

import re
matchInt = re.match("^\+?[0-9]+([eE][0-9]+)?$",sti)
if matchInt:
    return sti

This regular expression matches against all (positive) integers shown regularly or in scientific notation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top