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

前端 未结 7 2158
南方客
南方客 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 21:56

    This code could be a little bit longer, but straight forward and easy to maintain

    from pyparsing import Word, nums, OneOrMore
    
    integer = Word(nums)
    
    text = "blah blah (4,301) blah blah " 
    
    parser = OneOrMore(integer)
    
    iterator = parser.scanString( text )
    
    try:
        while True:
            part1 =  iterator.next()
            part2 =  iterator.next()
    except:
        x =  part1[0][0][0] + '.' +part2[0][0][0]
        print -float(x)
    

    Produces: -4.301

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-19 22:05

    For Python 3.6, and also handles '-' as 0, and strips excess empty spaces:

    def clean_num(num_string):
        bad_chars = '(),-'
        translator = str.maketrans('', '', bad_chars)
        clean_digits = num_string.translate(translator).strip()
    
        if clean_digits == '':
            return 0
        elif '(' in num_string:
            return -float(clean_digits)
        else:
            return float(clean_digits) 
    
    0 讨论(0)
  • 2021-02-19 22:08

    Presumably you want to handle positive numbers as well as negative, which is missing from many of the answers thus far. I'm going to add a bit to the answer from mogul.

    import locale
    locale.setlocale( locale.LC_ALL, '')
    my_str = '( 4,301 )'
    positive = my_str.translate(None, '()')
    result = locale.atoi(positive) if positive == my_str else -locale.atoi(positive)
    
    0 讨论(0)
  • 2021-02-19 22:11

    The simplest way is:

    my_str = "(4,301)"
    num = -int(my_str.translate(None,"(),"))
    
    0 讨论(0)
提交回复
热议问题