From the documentation of re.findall
:
If one or more capturing groups are present in the pattern, return a list of groups;
So if your pattern has a group, it will return the group. In your first example it will not return anything because it cannot find the matched group, and the second example will only return the group.
What you seek can be accomplished with re.search
https://docs.python.org/3/library/re.html#re.regex.search:
>>> re.search(r"(ab)?c", "c")
<_sre.SRE_Match object; span=(0, 1), match='c'>
>>> re.search(r"(ab)?c", "abc")
<_sre.SRE_Match object; span=(0, 3), match='abc'>
You can retrieve the groups by calling .groups()
on the result of the call
If you don't want to search
in a string but instead check that the string matches a pattern (and potentially see the groups), use re.match (see search vs match for details on how they differ).