0

I'm writing a Python program to convert a set of input strings into integers, then print them out. The input strings do not need to be integers (for example, they can be "udai2"), in which case, I want to print out that the string is not valid.

My original though was to simply convert each string to an integer using the int function, like int(input_str). Then, I'd surround this code with a try catch, to catch when the conversion wouldn't work (and hence the input was not a valid input):

    try:
        print(int(item))
    except:
        print("Not a valid input")

However, given a large input size, I'm worried that this isn't the most performant way to do this, since the except portion of the try-except really hurts performance when it runs. Is there a faster way to do this?

Bob Dole
  • 345
  • 1
  • 3
  • 11
  • 2
    Are you "worried that it will be slow" or it actually is performing slow?? – jamylak Jan 29 '18 at 17:10
  • Possible duplicate of [How can I check if a string represents an int, without using try/except?](https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except) – Yonas Kassa Jan 29 '18 at 17:23

1 Answers1

0

Depending on how frequently non-ints appear in your input file, you could read them all in a loop inside a try-catch, maintain a counter at each read, and thus find out which one was wrong if an exception occurs. This could offer some advantage if non-ints are relatively rare.

The try - catch should in turn be inside an outer while loop that restarts the inner while loop (the read loop) one number after the faulty one as long as there's data left.

In that way you won't have to enter lots of try blocks. But in general indeed first find out if there really is a problem before introducing any of this complexity.

Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45