Skip to main content
 首页 » 编程设计

python之从字符串到整数的转换

2025年05月04日25shihaiming

我正在通过 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: '' 

请您参考如下方法:

稍微更pythonic的方式:

i = int(csq) if csq else None