从字符串到整数的转换

Conversion From String To Int

我正在通过 COM 端口与调制解调器通信以接收 CSQ 值。

response = ser.readline()
csq = response[6:8]

print type(csq)

returns 以下内容:

<type 'str'> and csq is a string with a value from 10-20

为了进一步计算,我尝试将 "csq" 转换为整数,但是

i=int(csq)

returns 以下错误:

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

您的错误消息表明您正在尝试将空字符串转换为 int,这会导致问题。

将您的代码包装在 if 语句中以检查空字符串:

if csq:
    i = int(csq)
else:
    i = None

请注意,空对象(空列表、元组、集合、字符串等)在 Python 中的计算结果为 False

作为替代方案,您可以将代码放在 try-except-block 中:

try:
    i = int(csq)
except:
    # some magic e.g.
    i = False 

一种稍微更pythonic的方式:

i = int(csq) if csq else None