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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With