Search code examples
pythonbeautifulsouptypecasting-operator

Typecasting Error in Python


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))

The following is the error message.I thought typecasting from str to int would be simple but still i came across this error.I am a beginner in python so sorry if there has been any silly mistake in my code.

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'

Solution

  • The error is self explaining, a contains the string '1,373,541,278', and that is not a format Python can handle.

    We can however remove the comma's from the string, with:

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

    But it is possible that for some elements, you will have to do additional processing.