Click2Death
Click2Death

Reputation: 786

python re.sub with re.search not working as expected

I'm trying to generate output file name and path using timestamp. All the parts works as expected, but re.sub is not giving me the result I want. What I'm doing wrong here?

>>> a = r'\output\End-of-Day\{%Y\%m\%d\UINVDEFF securities %m.%d.%Y}.xlsx'
>>> b = re.search(r'(?P<timestamp>\{[^}]*(%[A-Za-z])[^{]*\})', a)
>>> b.group('timestamp')
'{%Y\\%m\\%d\\UINVDEFF securities %m.%d.%Y}'

>>> now
datetime.datetime(2014, 8, 18, 11, 43, 47, 55000)

>>> now.strftime(b.group('timestamp'))[1:-1]
'2014\\08\\18\\UINVDEFF securities 08.18.2014'

>>> re.sub(b.group('timestamp'), now.strftime(b.group('timestamp'))[1:-1], a)
'\\output\\End-of-Day\\{%Y\\%m\\%d\\UINVDEFF securities %m.%d.%Y}.xlsx'

Expecting '\output\End-of-Day\2014\08\18\UINVDEFF securities 08.18.2014.xlsx'

Upvotes: 2

Views: 97

Answers (1)

enrico.bacis
enrico.bacis

Reputation: 31544

The re.sub call is interpreting its first argument as a regex pattern:

{%Y\\%m\\%d\\UINVDEFF securities %m.%d.%Y}

When you just want to replace a substring with another in a string use string.replace:

a.replace(b.group('timestamp'), now.strftime(b.group('timestamp'))[1:-1])

Upvotes: 2

Related Questions