Philip McQuitty
Philip McQuitty

Reputation: 1077

Convert str to float explicitly in Python 3

I am gettting a "TypeError: Can't convert 'float' object to str implicitly" error because I am trying to divide a float by a string.

I am trying to cast the string to a float, but am still getting an error.

The string 'empNumber', is all digits but has a comma (ex: 112,000) - hence the "replace" function to strip the comma. I am drawing an error when I try to divide "final/decimal". How can I fix this type error?

def revPerEmployee():
    for ticker in sp500short:
        searchurl = "http://finance.yahoo.com/q/ks?s="+ticker
        f = urlopen(searchurl)
        html = f.read()
        soup = BeautifulSoup(html, "html.parser")

        searchurlemp = "http://finance.yahoo.com/q/pr?s="+ticker+"+Profile"
        femp = urlopen(searchurlemp)
        htmlemp = femp.read()
        soupemp = BeautifulSoup(htmlemp, "html.parser")

        try:
            revenue2 = soup.find("td", text="Revenue (ttm):").find_next_sibling("td").text
            empCount2 = soupemp.find("td", text="Full Time Employees:").find_next_sibling("td").text 

        except:
            revenue2 = "There is no data for this company"
            empCount2 = "There is no data for this company"         

        if revenue2 == "There is no data for this company" or empCount2 == "There is no data for this company":
            lastLetter = ticker+": There is no data for this company"
        else:
            lastLetter = revenue2[len(revenue2)-1:len(revenue2)]
            empNumber = empCount2.replace(",", "")
            decimal = float(empNumber)

        if lastLetter == "B":
            result = revenue2[:-1]
            revNum = float(result)
            final = revNum * 1000000000.0
            revPerEmp = final/decimal
            print(ticker+": "+revPerEmp)

        elif lastLetter == "M":
            result = revenue2[:-1]
            revNum = float(result)
            final = revNum * 1000000.0
            #newnum = "{:0,.2f}".format(final)
            revPerEmp = final/decimal
            print(ticker+": "+revPerEmp)

        elif lastLetter == "K":
            result = revenue2[:-1]
            revNum = float(result)
            final = revNum * 1000.0
            #newnum = "{:0,.2f}".format(final)
            revPerEmp = final/decimal
            print(ticker+": "+revPerEmp)

        else:
            print(lastLetter)

Upvotes: 1

Views: 242

Answers (2)

Sci Prog
Sci Prog

Reputation: 2691

The problem is that your program assumes that what is obtained from the URL request is a number in the form of digits followed by a suffix (K, M or B). This is not tested for.

There are also two suggestions to improve your code. First, you do use a try ... except clause to check when data cannot be obtained. You can also use it if conversion fails. The message "There is no data for this company" could be printed in the except clause.

Second, you have three if clauses very much alike, suggesting they can be condensed. A python dictionary can be used for the suffix values.

SUFFIX_VALUES = { 'K': 1000.0, 'M': 1000000.0, 'B': 1000000000.0 }
try:
  # taken from your code
  revenue2 = soup.find("td", text="Revenue(ttm):").find_next_sibling("td").text
  empCount2 = soupemp.find("td", text="Full Time Employees:").find_next_sibling("td").text 
  revNum = float(revenue2[:-1])
  empNumber = empCount2.replace(",", "")
  decimal = float(empNumber)
  lastLetter = revenue2[-1]
  final = revNum * SUFFIX_VALUES[lastLetter]
  revPerEmp = final/decimal
  print("%s: %d" % (ticker, revPerEmp))
except:
  print(ticker + ": There is no data for this company")

Now, if data is missing from the URL request, if conversion fails, or if the suffix is wrong, the program will execute the except clause.

Upvotes: 1

Amadan
Amadan

Reputation: 198556

17 + "orange" is nonsense, you can't add numbers and strings. You want

print("%s: %s" % (ticker, revPerEmp))

(you can switch %s for other formats, like %.2f), or

print(str(ticker) + ": " + str(revPerEmp))

Upvotes: 4

Related Questions