【问题标题】:How do I print a decimal number from a string in python3?如何从 python3 中的字符串打印十进制数?
【发布时间】:2021-08-05 13:06:42
【问题描述】:

我正在尝试打印字符串“rating”中的第一个十进制数字。

代码如下:

rating = soup.find("span", attrs={"class", "a-icon-alt"}).get_text().strip()
print(rating)

给出输出:

4.3 out of 5 stars

我希望输出是:

4.3

但如果我使用代码:

rating = soup.find("span", attrs={"class", "a-icon-alt"}).get_text().strip()[0]
print(rating)

我得到的输出为:

4

我需要显示十进制数。我该怎么做?

我希望问题很清楚。

【问题讨论】:

  • 在您的第二个 sn-p 中将 strip() 更改为 split()

标签: python-3.x string web-scraping decimal


【解决方案1】:

你只是取字符串"4.3 out of 5 stars"的第一个字符,你需要用空格分割它,然后取第一个元素。

>>> "4.3 out of 5 stars".split(" ")[0]
'4.3'

所以你的最终解决方案是:

rating = soup.find("span", attrs={"class", "a-icon-alt"}).get_text().strip().split(" ")[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2012-09-25
    相关资源
    最近更新 更多