[英]Python - Make sure string is converted to correct Float
I have possible strings of prices like: 我有可能这样的价格字符串:
20.99, 20, 20.12
Sometimes the string could be sent to me wrongly by the user to something like this: 有时,用户可能会将字符串错误地发送给我,如下所示:
20.99.0, 20.0.0
These should be converted back to : 这些应该转换回:
20.99, 20
So basically removing anything from the 2nd . 所以基本上从第二个删除任何东西。 if there is one. 如果有一个。
Just to be clear, they would be alone, one at a time, so just one price in one string 只是要清楚,它们将是单独的,一次只能一个,所以在一个字符串中只有一个价格
Any nice one liner ideas? 有什么不错的想法吗?
For a one-liner, you can use .split()
and .join()
: 对于单行代码,可以使用.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'
You could do something like this 你可以做这样的事情
>>> s = '20.99.0, 20.0.0'
>>> s.split(',')
['20.99.0', ' 20.0.0']
>>> map(lambda x: x[:x.find('.',x.find('.')+1)], s.split(','))
['20.99', ' 20.0']
Look at the inner expression of find. 看一下find的内在表达。 I am finding the first '.' 我正在找到第一个“。” and incrementing by 1 and then find the next '.' 并递增1,然后找到下一个“”。 and leaving everything from that in the string slice operation. 并将所有内容留在字符串切片操作中。
Edit: Note that this solution will not discard everything from the second decimal point, but discard only the second point and keep additional digits. 编辑:请注意,此解决方案不会丢弃第二个小数点后的所有内容,而是仅丢弃第二个点并保留其他数字。 If you want to discard all digits, you could use eg @Blender's solution 如果要舍弃所有数字,可以使用@Blender的解决方案
It only qualifies as a one-liner if two instructions per line with a ;
如果每行有两个指令,且仅带有一行,则它仅相当于单线;
count, but here's what I came up with: 数,但这是我想出的:
>>> x = "20.99.1234"
>>> s = x.split("."); x = s[0] + "." + "".join(s[1:])
>>> x
20.991234
It should be a little faster than scanning through the string multiple times, though. 但是,它应该比多次扫描字符串快一些。 For a performance cost, you can do this: 为了提高性能,您可以执行以下操作:
>>> x = x.split(".")[0] + "." + "".join(x.split(".")[1:])
For a whole list: 对于整个列表:
>>> def numify(x):
>>> s = x.split(".")
>>> return float( s[0] + "." + "".join(s[1:]))
>>> x = ["123.4.56", "12.34", "12345.6.7.8.9"]
>>> [ numify(f) for f in x ]
[123.456, 12.34, 12345.6789]
If you are looking for a regex based solution and your intended behaviour is to discard everthing after the second .(decimal)
than 如果您正在寻找基于正则表达式的解决方案,并且您的预期行为是抛弃第二个.(decimal)
>>> st = "20.99.123"
>>> string_decimal = re.findall(r'\d+\.\d+',st)
>>> float(''.join(string_decimal))
20.99
>>> s = '20.99, 20, 20.99.23'
>>> ','.join(x if x.count('.') in [1,0] else x[:x.rfind('.')] for x in s.split(','))
'20.99, 20, 20.99'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.