Match.groupdict: Meaning of default argument?
Loris Bennett
loris.bennett at fu-berlin.de
Tue May 3 10:43:48 EDT 2022
Julio Di Egidio <julio at diegidio.name> writes:
> On Friday, 29 April 2022 at 09:50:08 UTC+2, Loris Bennett wrote:
>> Hi,
>>
>> If I do
>>
>> import re
>> pattern = re.compile(r'(?P<days>\d*)(-?)(?P<hours>\d\d):(?P<minutes>\d\d):(?P<seconds>\d\d)')
>> s = '104-02:47:06'
>> match = pattern.search(s)
>> match_dict = match.groupdict('0')
>>
>> I get
>>
>> match_dict
>> {'days': '104', 'hours': '02', 'minutes': '47', 'seconds': '06'}
>>
>> However, if the string has no initial part (corresponding to the number of
>> days), e.g.
>>
>> s = '02:47:06'
>> match = pattern.search(s)
>> match_dict = match.groupdict('0')
>>
>> I get
>>
>> match_dict
>> {'days': '', 'hours': '02', 'minutes': '47', 'seconds': '06'}
>>
>> I thought that 'days' would default to '0'.
>>
>> What am I doing wrong?
>
> You tell, but it's quite obvious that you (just) run a regex on a string and captures are going to be strings: indeed, '02' is not a number either...
>
> Julio
I am not sure what you are trying to tell me. I wasn't expecting
anything other than strings. The problem was, as Stefan helped me to
understand, that I misunderstood what 'participating in the match'
means.
Cheers,
Loris
--
This signature is currently under construction.
More information about the Python-list
mailing list