从字符串到中的转换

2024-09-28 22:24:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

print type(csq)

返回以下内容:

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

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

i=int(csq)

返回以下错误:

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

Tags: and端口com调制解调器readlineisresponsetype
3条回答

一种稍微更像Python的方式:

i = int(csq) if csq else None

或者,您可以将代码放入try except块中:

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

错误消息显示您正试图将空字符串转换为int,这将导致问题。你知道吗

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

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

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

相关问题 更多 >