Reputation: 257
if re.findall(r"i am .*", a):
reg = re.compile(r" i am ([\w]+).*?$")
print('How long have you been {}?'.format(*reg.findall(a)))
So if i input:
i am struggling with life...
it should output:
How long have you been struggling?
But for some reason i get a tuple error?
By the way a is just an input field.
Traceback (most recent call last):
File "program.py", line 14, in <module>
print('How long have you been {}?'.format(*reg.findall(a)))
IndexError: tuple index out of range
Upvotes: 1
Views: 574
Reputation: 1121744
Your second regular expression doesn't match:
re.compile(r" i am ([\w]+).*?$")
because it starts with a space. Remove that initial space and it works fine:
>>> a = 'i am struggling with life...'
>>> reg = re.compile(r" i am ([\w]+).*?$")
>>> reg.findall(a)
[]
>>> reg = re.compile(r"i am ([\w]+).*?$")
>>> reg.findall(a)
['struggling']
The exception you see is thrown because the .format()
method receives positional arguments as a tuple, tries to look up item 0 and as it was passed an empty set of arguments you get the IndexError
.
Upvotes: 2