简体   繁体   English

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

[英]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.

相关问题 检查字符串是否可以在 Python 中转换为浮点数 - Checking if a string can be converted to float in Python Python, 判断一个字符串是应该转换成Int还是Float - Python, Determine if a string should be converted into Int or Float Python:如何使python计算总和以确保输入正确? - Python: how to make python calculate a sum to make sure an input is correct? 快速检查字符串是否可以在python中转换为float或int - Fast checking if a string can be converted to float or int in python 在循环中将从字符串转换为浮点数的数字列表相乘(Python)时遇到问题 - Trouble in multiplying list of numbers converted from string to float in a loop (Python) 字符串'-1'无法转换为float - string '-1' can't be converted to float 浮点数组未转换为 int:Python - Float Array is not converted to int: Python Python - 字符串格式(如何在不将浮点数转换为字符串的情况下限制小数) - Python - String Formatting (How to Limit Decimal Without the Float Getting Converted Into String) 不确定解决方案是否适用于python类 - Not sure solution is correct for python classes python中确保字符串适合作为文件名的优雅方式? - Elegant way in python to make sure a string is suitable as a filename?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM