1

I have the followring script:

#!/usr/bin/python3
f = open('importaciones2015-2016SFe-utf8.csv')
lineas = f.readlines()[1:]

for linea in lineas:
    rubro, producto, unidad , ant , actual = linea.split(";")
    print(int(actual.replace(".","")) - int(ant.replace(".","")))

f.close()

It works, but I wonder if there is a better way to substract numbers with thousands separators, instead of using replace.

user2864740
  • 60,010
  • 15
  • 145
  • 220
sebelk
  • 565
  • 1
  • 6
  • 16
  • Strings representing numbers are not numbers and do not support arithmetic math operations. For example: `"1.000"` is a string representing the number 1000 (in a locale where `.` is used as the thousands separator). `int("1000")` results in `1000`, and `1000` is a number. The `replace` is not related to the subtraction / math operation as the subtraction / math is done on the results of converting the strings to numbers (with `int`). – user2864740 Nov 19 '16 at 21:48
  • 2
    So the actual question might be: "How to convert localized number representations to integers?" (It's a localization question.) – user2864740 Nov 19 '16 at 21:53
  • You can use the `locale` module. If you do `locale.setlocale(locale.LC_ALL,'it_IT.UTF-8')` (assuming this is Italian and you have the Italian locale installed and this is a unix system) then you can do `locale.atoi(actual)`. But its different on windows. There are quite a few posts on this ... here are a couple of interesting samples http://stackoverflow.com/questions/1779288/how-do-i-use-python-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-th and http://stackoverflow.com/questions/955986/what-is-the-correct-way-to-set-pythons-locale-on-windows – tdelaney Nov 19 '16 at 23:42

0 Answers0