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

前端 未结 7 2202
南方客
南方客 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: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) 
    

提交回复
热议问题