【问题标题】:Typecasting Error in Python [duplicate]Python中的类型转换错误[重复]
【发布时间】:2018-02-15 08:40:25
【问题描述】:
pop=x.nextSibling()[0]  # pop="Population: 1,414,204"
pre_result=pop.text.split(" ") #pre_result=['Population:','1,414,204']
a=pre_result[1] # a='1,414,204'
result=int(a) #Error pops over here.Tried int(a,2) by searching answers in internet still got an error.
print(result) 
print(type(result))

以下是错误消息。我认为从 str 到 int 的类型转换很简单,但我还是遇到了这个错误。我是 python 的初学者,如果我的代码中有任何愚蠢的错误,非常抱歉。

File "C:\Users\Latheesh\AppData\Local\Programs\Python\Python36\Population Graph.py", line 14, in getPopulation
    result=int(a)
ValueError: invalid literal for int() with base 10: '1,373,541,278'

【问题讨论】:

  • 这有什么不清楚的地方? Python如何直接解析'1,373,541,278'
  • 使用逗号分隔数字在(我认为)中欧以外是不常见的,因此您必须在解析之前将其删除
  • 哈哈,我明白了。我现在意识到这是一个多么愚蠢的问题。谢谢大家!
  • 没问题,每个人都会遇到=)

标签: python beautifulsoup typecasting-operator


【解决方案1】:

错误是自我解释的,a 包含字符串 '1,373,541,278',这不是 Python 可以处理的格式。

然而,我们可以从字符串中删除逗号,使用:

result=int(a.replace(',', ''))

但可能对于某些元素,您将不得不进行额外的处理。

【讨论】:

  • 它确实有效,谢谢:)
猜你喜欢
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 2015-09-03
  • 1970-01-01
  • 2014-08-17
  • 2012-05-19
相关资源
最近更新 更多