Harry
Harry

Reputation: 13329

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?

Upvotes: 1

Views: 148

Answers (5)

RanRag
RanRag

Reputation: 49567

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

Upvotes: 1

Stefan Seemayer
Stefan Seemayer

Reputation: 2067

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 e.g. @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]

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174624

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

Upvotes: 1

Senthil Kumaran
Senthil Kumaran

Reputation: 56841

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.

Upvotes: 3

Blender
Blender

Reputation: 298166

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'

Upvotes: 8

Related Questions