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

前端 未结 7 2179
南方客
南方客 2021-02-19 21:52

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

7条回答
  •  时光取名叫无心
    2021-02-19 22:03

    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.

提交回复
热议问题