0

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?

2 Answers 2

1
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')
Sign up to request clarification or add additional context in comments.

1 Comment

Both of these work. I'm sure I tried many almost identical things, something about the try: except: must have been throwing me off.. Thanks for the correction!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.