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

前端 未结 7 2071
南方客
南方客 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-19 22:00

    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))
    

提交回复
热议问题