why do search and findall give different results?
result = re.search(r'Bat(wo)?man', 'The Adventures of Batman')
print(result) # found
re.findall(r'Bat(wo)?man', 'The Adventures of Batman') # empty list
why do search and findall give different results?
result = re.search(r'Bat(wo)?man', 'The Adventures of Batman')
print(result) # found
re.findall(r'Bat(wo)?man', 'The Adventures of Batman') # empty list
When I run this, I don't get an empty list, but a list containing a single empty string: ['']
.
From the docs (emphasis mine):
The result depends on the number of capturing groups in the pattern. If there are no groups, return a list of strings matching the whole pattern. If there is exactly one group, return a list of strings matching that group. If multiple groups are present, return a list of tuples of strings matching the groups. Non-capturing groups do not affect the form of the result.
You use a capturing group ((wo)?
), so the results only contain the part of the string that matched that group.
You can fix this by changing the group to a non-capturing group:
>>> print(re.findall(r'Bat(?:wo)?man', 'The Adventures of Batman'))
['Batman']