0

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'

1
  • Can the value of the date in the string change along with it's position or is it always "20220320"? Commented May 1, 2022 at 2:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.