从字符串转换为Int

moa*_*tze 1 python string converter python-2.7

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

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

print type(csq)
Run Code Online (Sandbox Code Playgroud)

返回以下内容:

<type 'str'> and csq is a string with a value from 10-20
Run Code Online (Sandbox Code Playgroud)

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

i=int(csq)
Run Code Online (Sandbox Code Playgroud)

返回以下错误:

invalid literal for int() with base 10: ''
Run Code Online (Sandbox Code Playgroud)

小智 5

稍微更加pythonic的方式:

i = int(csq) if csq else None
Run Code Online (Sandbox Code Playgroud)