2015-05-28 21 views
1

我通過COM端口與調制解調器通信以接收CSQ值。從字符串轉換爲Int

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: '' 
+0

不要忘記標記一個答案是正確的,以幫助那些在未來看到這個問題的人! – Scironic

回答

5

稍微更Python的方式:

i = int(csq) if csq else None 
3

您的錯誤消息顯示t你試圖將一個空字符串轉換成int這會導致問題。

總結你的代碼中的if語句來檢查空字符串:

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

注意,空對象(空列表,元組,集合,字符串等)評估在Python False

1

作爲替代,你可以把你的代碼的嘗試 - 除了塊內:

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