Python - 确保字符串转换为正确的 Float

标签 python regex

我有可能的价格字符串,例如:

20.99, 20, 20.12

有时字符串可能会被用户错误地发送给我,如下所示:

20.99.0, 20.0.0

这些应该被转换回:

20.99, 20

所以基本上从 2nd 中删除任何内容。如果有的话。

需要说明的是,他们将是单独的,一次一个,所以一个字符串中只有一个价格

有什么好的类轮创意吗?

最佳答案

对于单行代码,您可以使用 .split().join():

>>> '.'.join('20.99.0'.split('.')[:2])
'20.99'
>>> '.'.join('20.99.1231.23'.split('.')[:2])
'20.99'
>>> '.'.join('20.99'.split('.')[:2])
'20.99'
>>> '.'.join('20'.split('.')[:2])
'20'

关于Python - 确保字符串转换为正确的 Float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12067959/

相关文章:

python - os.system 在 raw_input() 和 file.readlines() 中的输入表现不同

Ruby - 如何在特定关键字之前分割字符串

regex - 如何使用正则表达式使我的 sparql 查询更快?

python - 如何根据pandas数据框中的行和列分隔条目

python - 将 Count 连接到 pandas 中的原始 DataFrame

python - 如何正确写出 Pandas 系列中的 TSV 文件?

python - django如何在背对背注释中的同一字段上使用Max和Count

Ruby:从字符串生成新的正则表达式

regex - Golang中的 "Matches the contents of the group of the same number"怎么办?

java - 在java正则表达式中捕获同一组的多个实例