【问题标题】:Conversion From String To Int从字符串到整数的转换
【发布时间】:2015-08-10 23:33:03
【问题描述】:

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

【问题讨论】:

  • 不要忘记将答案标记为正确,以帮助将来查看此问题的人!

标签: python string python-2.7 converter


【解决方案1】:

您的错误消息显示您正在尝试将空字符串转换为int,这会导致问题。

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

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

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

【讨论】:

    【解决方案2】:

    作为替代方案,您可以将代码放在 try-except-block 中:

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

    【讨论】:

      【解决方案3】:

      一种更 Pythonic 的方式:

      i = int(csq) if csq else None
      

      【讨论】:

        猜你喜欢
        • 2016-06-08
        • 1970-01-01
        • 2017-10-16
        • 2014-02-20
        • 2015-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多