【问题标题】:can't convert string to integer-python无法将字符串转换为整数-python
【发布时间】:2014-02-06 16:05:20
【问题描述】:

我在这样的元组中有一个字符串:

params': {
    'rtinseconds': '57.132',
    **'charge': '3+'**, 
    'pepmass': (822.6547241, None), 
    title': '20130630_006.d, MS/MS of 822.6547241 3+ at 0.9522 mins'
}

我正在尝试读取电荷“3+”的值并将其转换为整数值 3。

我尝试了以下代码,其中读取了字符串中的第一个字符并将其存储在单独的变量中,然后尝试将其转换为 int,但不起作用。 3 的类型仍然是 str。有人有什么建议吗?

        temp_z = item['params']['charge']
        z = temp_z[0:1]
        str(z)
        int(z) 

【问题讨论】:

  • z = int(temp_z[0:1]), int 返回一个新对象。
  • 顺便说一句,你最好使用z = int(temp_z.replace("+","")),如果收费超过10次。
  • 非常感谢阿什维尼!!那行得通!
  • 谢谢 JL!........

标签: python string dictionary tuples


【解决方案1】:

在简单的情况下:

z = int(params['charge'].replace('+',''))

但是,如果您的商品可能有负电荷,您可能会想要:

if '+' in params['charge']:
    z = int(params['charge'].replace('+',''))
else:
    z = -int(params['charge'].replace('-',''))

【讨论】:

    猜你喜欢
    • 2012-10-22
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    相关资源
    最近更新 更多