如何转换₹22000字符串在python中浮动

2024-09-29 23:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

回溯(最近一次呼叫最后一次): 文件“scrap.py”,第13行,在 转换价格=浮动(价格[:5]) ValueError:无法将字符串转换为浮点:'₹\xa022,'


Tags: 文件字符串py价格浮点scrapvalueerrorxa022
3条回答

由于^{}函数只允许某些字符,因此必须过滤掉所有不属于浮点数的字符

您可以使用regular expression (regex)查找浮点数中允许的所有字符。例如,要查找所有数字、减号、加号和点,请执行以下操作:

float_regex = re.compile(r'[-.+\d]+')

在输入字符串中查找所有这些字符并将它们连接在一起:

clean_input = ''.join(float_regex.findall(input_string))

然后才转换成浮点

例如:

>>> import re
>>> float_regex = re.compile(r'[-.+\d]+')
>>> input_string = '₹\xa022,'
>>> clean_input = ''.join(float_regex.findall(input_string))
>>> float(clean_input)
22.0

尝试:

>>> converted_price = float(price[1:])
>>> converted_price
22000.0

你可以用

dirty = "₹22000.83"

try:
    cleaned = float("".join(char for char in dirty if
                            char in ["-", "."] or char.isdigit()))
    print(cleaned)
except ValueError:
    pass

产生

22000.83

相关问题 更多 >

    热门问题