Convert a number enclosed in parentheses (string) to a negative integer (or float) using Python?

The simplest way is:

my_str = "(4,301)"
num = -int(my_str.translate(None,"(),"))

Since you are reading from a system that put in thousands separators, it's worth mentioning that we are not using them the same way all around the world, which is why you should consider using a locale system. Consider:

import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
my_str = "(4,301)"
result = -locale.atoi(my_str.translate(None,"()"))

Assuming just removing the , is safe enough, and you may wish to apply the same function to values that may contain negative numbers or not, then:

import re
print float(re.sub(r'^\((.*?)\)$', r'-\1', a).replace(',',''))

You could then couple that with using locale as other answers have shown, eg:

import locale, re

locale.setlocale(locale.LC_ALL, 'en_GB.UTF-8')
print locale.atof(re.sub('^\((.*?)\)$', r'-\1', a))

Tags:

Python