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

匿名 (未验证) 提交于 2019-12-03 03:05:02

问题:

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 encountered in accounting applications.

回答1:

The simplest way is:

my_str = "(4,301)" num = -int(my_str.translate(None,"(),"))


回答2:

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,"()"))


回答3:

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


回答4:

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)


回答5:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!