Home > database >  replace the date section of a string in python
replace the date section of a string in python

Time:05-02

if I have a string 'Tpsawd_20220320_default_economic_v5_0.xls'.

I want to replace the date part (20220320) with a date variable (i.e if I define the date = 20220410, it will replace 20220320 with this date). How should I do it with build-in python package? Please note the date location in the string can vary. it might be 'Tpsawd_default_economic_v5_0_20220320.xls' or 'Tpsawd_default_economic_20220320_v5_0.xls'

CodePudding user response:

Yes, this can be done with regex fairly easily~

import re

s = 'Tpsawd_20220320_default_economic_v5_0.xls'
date = '20220410'
s = re.sub(r'\d{8}', date, s)
print(s)

Output:

Tpsawd_20220410_default_economic_v5_0.xls

This will replace the first time 8 numbers in a row are found with the given string, in this case date.

  • Related