简体   繁体   English

从字符串到整数的转换

[英]Conversion From String To Int

I'm communicating with a modem via COM port to recieve CSQ values. 我正在通过COM端口与调制解调器进行通信,以接收CSQ值。

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

print type(csq)

returns the following: 返回以下内容:

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

For further calculation I try to convert "csq" into an integer, but 为了进一步计算,我尝试将“ csq”转换为整数,但是

i=int(csq)

returns following error: 返回以下错误:

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

一种稍微更Python化的方式:

i = int(csq) if csq else None

Your error message shows that you are trying to convert an empty string into an int which would cause problems. 您的错误消息表明您正在尝试将空字符串转换为int ,这将导致问题。

Wrap your code in an if statement to check for empty strings: 将代码包装在if语句中以检查空字符串:

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

Note that empty objects (empty lists, tuples, sets, strings etc) evaluate to False in Python. 请注意,空对象(空列表,元组,集合,字符串等)在Python中的值为False

As alternative you can put your code inside an try-except-block: 或者,您可以将代码放在try-except-block中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM