gpt4 book ai didi

python - 在 Python 3 中将 str 显式转换为 float

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:49 25 4
gpt4 key购买 nike

我收到“TypeError:无法将‘float’对象隐式转换为 str”错误,因为我试图用字符串除以 float 。

我试图将字符串转换为 float ,但仍然出现错误。

字符串“empNumber”全是数字,但有一个逗号(例如:112,000)——因此“替换”功能会去除逗号。当我尝试划分“final/decimal”时出现错误。如何修复此类型错误?

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)

最佳答案

17 + "orange" 是废话,不能把数字和字符串相加。你要

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

(您可以将 %s 切换为其他格式,例如 %.2f),或者

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

关于python - 在 Python 3 中将 str 显式转换为 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35568979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com