Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

In Python, what is the simplest way to convert a number enclosed in parentheses (string) to a negative integer (or float)?

For example, '(4,301)' to -4301, as commonly encountered in accounting applications.

like image 744
silvernightstar Avatar asked May 23 '13 15:05

silvernightstar


1 Answers

For localized numbers, I use this:

def clean_number(text):
    import locale
    locale.setlocale(locale.LC_NUMERIC, "Portuguese_Brazil.1252")
    tbl = str.maketrans('(', '-', 'R$ )')
    return locale.atof(text.translate(tbl))

Works with Python 3.8. The first parenthesis is replaced with the minus sign, the second is removed. Also removes spaces and the monetary sign.

like image 195
Julio Batista Silva Avatar answered Oct 03 '22 13:10

Julio Batista Silva