Python – How to convert String to float

In Python, we can use float() to convert String to float.


num = "3.1415"

print(num)
print(type(num))  # str

pi = float(num)  # convert str to float

print(pi)
print(type(pi))  # float

Output


3.1415
<class 'str'>
3.1415
<class 'float'>

References

  1. Python docs – float()

2 comments on “Python – How to convert String to float

  1. Please help me out to resolve below error

    If I write like this

    n = input(“Enter a numerical expression: “)
    print(float(n))

    got below error

    print(float(n))
    ValueError: could not convert string to float: ‘5.5+6.5’

    Expected Output: 12

  2. def priceOf(stockSymbol):
    html = _readHTML(stockSymbol)
    trade = html.find(‘yfs_l84’, 0)
    beg = html.find(‘>’, trade)
    end = html.find(‘‘, beg)
    price = html[beg + 1: end]
    price = price.replace(‘,’, ”)
    return (float(str(price)))
    This piece of could not convert string to float….The very last line…can you help in converting this string to a float…please..

Leave a Comment

Your email address will not be published. Required fields are marked *