Home > Enterprise >  How to convert a string to float if the thousands and decimals points are the same
How to convert a string to float if the thousands and decimals points are the same

Time:11-24

I would like to convert an string like '-2.676.15024' and '2.938.45500' to float? My data base has some examples like this, where the number(string) has thousands and decimals separators with the same symbol, in these cases a point.

CodePudding user response:

IIUC you want to remove all dots except the last one.

You can use a regex:

import re

s = '-2.676.15024'
float(re.sub('\.(?=.*\.)', '', s))

output: -2676.15024

Alternative using rsplit and join:

s = '-2.676.15024'
float('.'.join(map(lambda x: x.replace('.', ''), s.rsplit('.', 1))))

NB. this is assuming there is always a decimal part. If not you have to clarify the conditions for deciding whether a dot is a decimal or thousand separator

CodePudding user response:

You can try with

test = '-2.938.45500'
result = float(test.replace('.', '', test.count('.') - 1))
print(result)

CodePudding user response:

s='-2.676.15024'
index=s.find('.')
print(float(s[:index] s[index 1:]))

output:-2676.15024

  • Related