JPV
JPV

Reputation: 1079

Conversion types in Python

I have the following code

text_file = open("up2017.txt", "r")
amount=[]
for line in text_file:

    fields =  line.strip().split(" ")
    amount.append(fields[-1])

list(map(float,amount))

And I get the following error

ValueError: could not convert string to float: '50.000,00'

The text files looks like

13.10    Ovf           12.10            50.000,00                50.000,00
30.10    Bgs                              30.10            12.000,00                62.000,00
30.11    Bgs                              30.11            12.000,00                74.000,00
15.12    Bgs                              15.12            53.528,36               127.528,36
30.12    Bgs                             30.12            12.000,00               139.528,36

Upvotes: 0

Views: 45

Answers (2)

Matias Cicero
Matias Cicero

Reputation: 26281

The correct way to do this is to use the appropriate locale.

For instance, on Spanish speaking countries it is very common to use . as the thousands separator and , as the decimal separator.

import locale
locale.setlocale(locale.LC_NUMERIC, 'es')
value = locale.atof('50.032,56') # yields float(50032.56)

In your case, you can do something like:

import locale
locale.setlocale(locale.LC_NUMERIC, 'es')

# ...

values = map(locale.atof, amount)

Upvotes: 3

Rafał
Rafał

Reputation: 705

Use the str.replace method:

amount.append(fields[-1].replace('.', '').replace(',', '.'))

Upvotes: 1

Related Questions