【问题标题】:invalid literal for int() with base 10: when trying with a value with "," present in it基数为 10 的 int() 的无效文字:尝试使用其中存在“,”的值时
【发布时间】:2016-06-01 04:04:36
【问题描述】:
>>> x='2,33'
>>> type(x)
<type 'str'>
>>> y=int(x)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    y=int(x)
ValueError: invalid literal for int() with base 10: '2,33'
>>>

我在尝试将另一个函数的返回值转换为 int 以进行计算时遇到问题。 问题在于该字符串中存在“,”,知道如何删除它。

【问题讨论】:

  • 要将字符串中的哪个整数转换成int

标签: python string int


【解决方案1】:

这取决于您想要实现的目标。如果您想在示例中保留 2 或 33,则可以使用:

>>> y = int(x.split(',')[0])
>>> y
2
>>> type(y)
<type 'int'>

如果你想连接两个值,你可以使用:

>>> z = int(x.replace(',', ''))
>>> z
233
>>> type(z)
<type 'int'>

【讨论】:

  • 感谢帮助 3kt
【解决方案2】:

假设你只想要整数部分,你可以尝试去掉逗号后面的部分,例如:

int(x[:x.find(',')])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 2013-05-31
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多