简体   繁体   中英

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() :

>>> '.'.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. I am finding the first '.' and incrementing by 1 and then find the next '.' 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

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

>>> 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM