-1

Target to modify:

Sample ="FST~C~D~170101 FST~C~D~170102 FST~C~D~170103 FST~C~D~170104"

I want to replace "170101","170102","170103","170104" with "170413", "170414","170415","170416"(the current date and days behind) The output should be:

"FST~C~D~170413 FST~C~D~170414 FST~C~D~0415 FST~C~D~170416"

I tried with replace() but failed. I know it is due a "string" is not allowed to be modified. Anyone can help on this!

deceze
  • 471,072
  • 76
  • 664
  • 811
X.Klein
  • 11
  • 1

2 Answers2

0

Because of the nature of your data there, you could probably benefit from slicing your data into variables and adding them to a list or dictionary. From there you can use a for loop to operate on specific values.

This should help with slicing: Is there a way to substring a string in Python?

>>> x = "FST~C~D~170101 FST~C~D~170102 FST~C~D~170103 FST~C~D~170104"
>>> a = x[:7]
>>> print(a)
'FST~C~D~'
>>> b = x[8:13]
>>> print(b)
170101

... continue this with the rest of your data

>>> mydict = {a:b,c:d,e:f,g:h}

Then with a dictionary of your values, operate on them. To do that here's a helpful answer: Replacing values in a Python list/dictionary?

I do hope this helps!

Community
  • 1
  • 1
beerandsmiles
  • 104
  • 3
  • 11
0

You could use a regex to find the old dates and define a function to calculate the new ones:

import re
from datetime import date, datetime

sample = "FST~C~D~170101 FST~C~D~170102 FST~C~D~170103 FST~C~D~170104"

def parse_yymmdd(yymmdd):
    return datetime.strptime(yymmdd, '%y%m%d').date()

first_date = parse_yymmdd('170101')

def replace_date(old_date):
    old_date = parse_yymmdd(old_date.group(0))
    new_date = date.today() + (old_date - first_date)
    return new_date.strftime('%y%m%d')

print(re.sub(r'(?<=FST~C~D~)\d+\b', replace_date, sample))
# "FST~C~D~170413 FST~C~D~170414 FST~C~D~170415 FST~C~D~170416"
Eric Duminil
  • 48,038
  • 8
  • 56
  • 100