【问题标题】:Could not convert negative string to a float无法将负字符串转换为浮点数
【发布时间】:2022-02-03 11:34:21
【问题描述】:
def net_value(count, wait):  
    wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@class='additional_percent_value']")))
    time.sleep(1)  
    net_profit = driver.find_elements_by_class_name("additional_percent_value")[0].text.split(" %")  
    net_profitfl = float(net_profit[0])

    if net_profitfl > 0.0:
        net_value = float(net_profit[0])
        profits.update({count: net_value})
        positive_color = {count: net_value}
        print(colored(f'{positive_color}', 'green'))
        return net_value

在字符串中使用正数时代码运行良好,但使用负数时会出现此错误:

{2: 8.59} {3: 3.01} {4: 7.3} {5: 6.83} {6: 1.52} {7: 0.25} {8: 0.25}  
Traceback (most recent call last):  
net_profitfl = float(net_profit[0])  
ValueError: could not convert string to float: '−1.54'

我尝试使用 list(map(float, net_profitstr[0]))np.array 而不是直接浮动,但它给了我同样的错误

【问题讨论】:

  • 无法复制。 float('-1.54') 有效。请提供minimal reproducible example
  • @DeepSpace:在float('−1.54') 上试一试(异常消息中显示的值)。

标签: python string type-conversion


【解决方案1】:

似乎第一个字符不是ASCII减号而是Unicode版本。因此改变:

net_profitfl = float(net_profit[0])

...到...

net_profitfl = float(net_profit[0].replace('\u2212', '-'))

【讨论】:

  • 完美运行。 Tnx :)
猜你喜欢
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多