提问人:Nelson Lamounier 提问时间:10/12/2022 最后编辑:uozcan12Nelson Lamounier 更新时间:10/12/2022 访问量:476
ValueError:无法将字符串转换为浮点数:“$50.50”
ValueError: could not convert string to float: '$50.50'
问:
我这里有这个python函数。但是,在运行时,我收到错误“无法将字符串转换为浮点数:'$50.50'”。我需要将输入添加为包含“$”符号的字符串,然后在后端将其转换为浮点数。该函数似乎只添加“50.50”作为输入。
def main():
dollars = dollars_to_float(input("How much was the meal? "))
percent = percent_to_float(input("What percentage would you like to tip? "))
tip = dollars * percent/100
print(f"Leave $" , str(tip) )
def dollars_to_float(d):
str.lstrip(d)
return float(d)
def percent_to_float(p):
str.rstrip(p)
return float(p)
main()
错误:
File "/Users/nelsonlamounier/indoor/indoor.py", line 13, in <module>
main()
File "/Users/nelsonlamounier/indoor/indoor.py", line 9, in dollars_to_float
return float(d)
File "/Users/nelsonlamounier/indoor/indoor.py", line 9, in dollars_to_float
return float(d)
ValueError: could not convert string to float: '$50.50'
答:
0赞
Xavier Cheng
10/12/2022
#1
只需删除数字前的 $,例如:
def dollars_to_float(d):
str.lstrip(d)
return float(d.replace("$",""))
评论
0赞
bn_ln
10/12/2022
此函数不适用于浮点数、整数或带有逗号的数字字符串,例如'$5,000'
1赞
msamsami
10/12/2022
#2
对于更一般的情况,请使用以下内容进行更新:dollars_to_float
def dollars_to_float(d):
d = ''.join([ch for ch in d if ch.isnumeric() or ch == '.'])
return float(d)
0赞
Nora
10/12/2022
#3
您的代码容易出错,因为单个空格字符已经能够破坏它。可以在此处找到货币到浮点数转换的更强大版本 使用价格通用解决方案从字符串中删除货币符号和文字
使用区域设置查看小数点字符(或 .)是什么,使用正则表达式删除除数字和小数点以外的所有字符。
import re
import locale
def dollars_to_float(price_string: str) -> float:
decimal_point_char = locale.localeconv()['decimal_point']
clean = re.sub(r'[^0-9'+decimal_point_char+r']+', '', str(price_string))
return float(clean)
0赞
CtrlZ
10/12/2022
#4
如果要从字符串的开头或结尾删除特定字符,请使用 strip()
在这种情况下,您的dollars_to_float和percent_to_float可以概括为:
def to_float(d):
return float(d.strip('$%'))
这样做的优点是支持字符串开头或结尾的 $ 和 % 字符。
但是,假设输入是这样的“$1,200”
由于千位分隔符,这将失败。另外,为什么要将功能限制在美元上。为什么不允许输入字符串的任意前导码 - 例如,1,200 美元或 1,234,50 英镑
这是解决这个问题的一个相当可靠的方法。
import re
from locale import LC_NUMERIC, setlocale, localeconv
class CC:
dp = None
def __init__(self):
if CC.dp is None:
setlocale(LC_NUMERIC, '')
dp = localeconv()['decimal_point']
CC.dp = f'[^0-9{dp}+-]+'
def conv(self, s):
return float(re.sub(CC.dp, '', s))
print(CC().conv('$1,200.5'))
print(CC().conv('£1,200'))
print(CC().conv('EUR1234.5'))
print(CC().conv('6543.21'))
输出:
1200.5
1200.0
1234.5
6543.21
评论
$
lstrip
rstrip
return float(d[1:])
return float(p[:-1])