I am using regex to calculate the value of a string that contains real numbers and addition, such as '3.4+5.2'. This is the code:
import re
a = str(raw_input())
counter = a.count('+')
for i in range(counter):
add = re.match('([\+\-]?\d+(?:\.\d+)?)\+([\+\-]?\d+(?:\.\d+)?)', a)
temp = float(add.groups()[0]) + float(add.groups()[1])
a = re.sub('([\+\-]?\d+(?:\.\d+)?)\+([\+\-]?\d+(?:\.\d+)?)', str(temp), a)
print a
It works fine for:
>>> a = '3+4'
'7.0'
>>> a = '3+4+5'
'12.0'
But, when I try to add more than twice:
>>> a = '3+4+5+6'
7.07.0
temp = float(add.groups()[0]) + float(add.groups()[1])
AttributeError: 'NoneType' object has no attribute 'groups'
Why does this error appear, how can it be fixed?
re.matchfinds nothing, so there's no group.re.matchreturnsNoneif there's no match. Trying to accessgroupsraisesAttributeError. (None.groups(...))a.split('+'), without regex?abecome7.07.0which does not have+-> no match.