I can't convert an empty string to integer using python

python, python-2.x

Solution

int('0'+s)

Prepend the string with a zero. Think of it as a miniature parsing step. I can't think of a case when this wouldn't work.

This is the use-case I had: Convert a numpy array of strings to integers.

def _intStrArray(pos): return int('0'+pos)
np.intStrArray = np.vectorize(_intStrArray)
print(arr)
array([['', '', '', '', '', '', '', '', '', '', '', '', ''],
       ['', '', '1', '', '', '2', '', '2', '', '', '', '', ''],
       ['', '2', '2', '', '3', '2', '', '', '2', '', '', '', ''],
       ['', '2', '', '3', '2', '2', '3', '4', '', '4', '', '', ''],
       ['', '', '3', '2', '2', '', '', '3', '3', '', '2', '1', ''],
       ['', '', '', '1', '2', '', '3', '2', '', '', '', '', ''],
       ['', '', '2', '', '2', '4', '3', '', '2', '1', '', '2', ''],
       ['', '', '', '', '', '', '2', '', '', '1', '', '1', ''],
       ['', '', '', '', '', '', '', '', '', '', '', '', '']], dtype=object)
print(np.intStrArray(arr))
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0],
       [0, 2, 2, 0, 3, 2, 0, 0, 2, 0, 0, 0, 0],
       [0, 2, 0, 3, 2, 2, 3, 4, 0, 4, 0, 0, 0],
       [0, 0, 3, 2, 2, 0, 0, 3, 3, 0, 2, 1, 0],
       [0, 0, 0, 1, 2, 0, 3, 2, 0, 0, 0, 0, 0],
       [0, 0, 2, 0, 2, 4, 3, 0, 2, 1, 0, 2, 0],
       [0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

After discovering just how messy my data was, I also added a `str()`. This is optional if the datatype is reliable.

def _intStrArray(pos): return int('0'+str(pos))
np.intStrArray = np.vectorize(_intStrArray)

Problem

I use pySerial to read data from serial port and I am trying to convert the string below to integer: ``` s=ser.read() int(s) ``` but i can't.The error i take is: ``` Traceback (most recent call last): File "C:\Documents and Settings\User\Desktop\ser1.py", line 24, in <module> int(s) ValueError: invalid literal for int() with base 10: '' ``` Do anyone know how to convert it? Thanks in advance!

Original source