Search code examples
python-3.5

how can I convert a text to float in python?


I will import exchange rate from a site and I will use exchange rate to calculate.I have no problem about importing.But I will import exchange rate as string.I must convert string to float to calculate.But I couldn't.I don't know where problem is.Section of Show some code is just a instance.It has same problem.

I will use data for calculation with exchange rate.

import requests
from bs4 import BeautifulSoup


url = "https://www.bloomberght.com"
response = requests.get(url)
icerik = response.content
soup = BeautifulSoup(icerik, "html.parser")
liste = []
liste2=[]
for i in soup.find_all("div", {"class", "line2"}):
    i =i.text
    liste.append(i.strip())

A=8*float(liste[2])
print(A)

Traceback (most recent call last): File "C:/Users/proin/PycharmProjects/software222/BBBBBBB.py", line 15, in A=8*float(liste[2]) ValueError: could not convert string to float: '6,5827'

Process finished with exit code 1


Solution

  • Use str.replace() to replace , to .. Then the conversion to float will work:

    import requests
    from bs4 import BeautifulSoup
    
    
    url = "https://www.bloomberght.com"
    response = requests.get(url)
    icerik = response.content
    soup = BeautifulSoup(icerik, "html.parser")
    liste = []
    liste2= []
    for i in soup.find_all("div", {"class", "line2"}):
        i = i.text
        liste.append(i.strip().replace(',', '.'))
    
    A=8*float(liste[2])
    print(A)
    

    Prints:

    52.6456