python - 我无法使用 python 将空字符串转换为整数

标签 python python-2.x

我使用 pySerial 从串行端口读取数据,我试图将下面的字符串转换为整数:

s=ser.read()
int(s) 

但我不能。我的错误是:

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: '' 

有人知道怎么转换吗? 提前致谢!

最佳答案

int('0'+s)

在字符串前加一个零。将其视为微型解析步骤。 我想不出这行不通的情况。

这是我的用例: 将 numpy 字符串数组转换为整数。

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]])

在发现我的数据有多乱之后,我还添加了一个str()。如果数据类型可靠,这是可选的。

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

关于python - 我无法使用 python 将空字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16299741/

相关文章:

python - PyMySQL、MySQL、Python : String formatting

python - 如何在 Python2.7.10 中使用 multiprocessing 创建子进程而不让子进程与父进程共享资源?

python - 为什么这种循环导入在 Python 2 中会失败,但在 Python 3 中却不会?

numpy - 使用 numpy 或 scipy 计算两组向量之间的欧几里得距离的最快方法

web-applications - 学习 Python 进行 Web 开发。 Python 2 还是 3?

python - 请对我的示例 Python 程序进行代码审查

python - 验证安装,如果已安装则打印版本,否则安装该包

python - 路径名打开时间太长?

python - 看起来相似的 Python for 循环之间的区别?

python - 刷新后Bokeh实时更新x_axis