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

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

    Since you are reading from a system that put in thousands separators, it's worth mentioning that we are not using them the same way all around the world, which is why you should consider using a locale system. Consider:

    import locale
    locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
    my_str = "(4,301)"
    result = -locale.atoi(my_str.translate(None,"()"))
    
    0 讨论(0)
提交回复
热议问题