Reputation: 99
Currently I have the following:
for child in root:
if child.attrib['startDateTime'] == fr'2019-11-10T{test_time}:\d{{2}}':
print('Found')
Which isn't working. The goal here is to match the datetime string with my own string where test_time
is formatted as 'HH:MM', and the seconds digits can be anything from 00 - 60.
Is this the correct approach for a problem like this? Or am I better off converting to datetime objects?
Upvotes: 1
Views: 7565
Reputation: 33107
It's not the f-string that's the problem. The r
prefix on a string doesn't mean "regex", it means "raw" - i.e. backslashes are taken literally. For regex, use the re
module. Here's an example using Pattern.match
:
import re
regex = fr'2019-11-10T{test_time}:\d{{2}}'
pattern = re.compile(regex)
for child in root:
if pattern.match(child.attrib['startDateTime']):
print('Found')
Upvotes: 5
Reputation: 781771
You can put a regexp in an f-string, but you need to use the re
module to match with it, not ==
.
if re.match(fr'2019-11-10T{test_time}:\d{{2}}', child.attrib['startDateTime']):
print('Found')
Upvotes: 2