0

I can't run the code below because of the 7th line value = int(qty)*int(price). I can only run it if I use the int() function inside the print() function. Is there a way I can define it's an integer before I ask it to print? The same for float?

file = open("C:\\file.txt","r")
for mid in file:
    qty = mid[38:53]
    qty = qty.lstrip("0")
    price = mid[75:86]
    price = price.lstrip("0")
    value = int(qty)*int(price)
    trades = [qty,price,value]
    print (trades)
file.close()

Shell-->

ValueError: invalid literal for int() with base 10: ''

Cœur
  • 37,241
  • 25
  • 195
  • 267
evicq
  • 11
  • 1
  • You can always ask it to be an integer. The string you must be passing may contain letters which make the compiler think its a hexadecimal or have a "." making it a float – cjds Jul 19 '16 at 19:05
  • 9
    Possible duplicate of [ValueError: invalid literal for int() with base 10: ''](http://stackoverflow.com/questions/1841565/valueerror-invalid-literal-for-int-with-base-10) – lonewaft Jul 19 '16 at 19:05
  • 1
    You can ask for the type using type(var) – sir_snoopalot Jul 19 '16 at 19:05
  • 2
    either qty or price are not something that can be converted to int. try to print them before the line `value = int(qty)*int(price)` to see whats inside. – Ronen Ness Jul 19 '16 at 19:06

2 Answers2

0

What's happening is that one of your items has either its price or quantity set to 0. When it's read in your code strips that 0 leaving you with an empty string, raising a ValueError when it is converted to an int.

You should probably remove the lstrips. At worst you will get numbers like "04" which the int constructor can handle anyway.

Trevor Merrifield
  • 4,541
  • 2
  • 21
  • 24
0

The following function return the integer value or None in case the string is not valid integer:

def parseInt(ss):
    try:
        return int(ss)
    except:
        return None

Use this function to check if the string is an integer:

for mid in file:
    qty = mid[38:53]
    qty = qty.lstrip("0")
    qty = parseInt(qty)

    price = mid[75:86]
    price = price.lstrip("0")
    price = parseInt(price)

    if qty != None and price != None:
        value = qty*price
        trades = [qty,price,value]
        print (trades)
file.close()
napuzba
  • 6,033
  • 3
  • 21
  • 32