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

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

提交回复
热议问题