I have a list of strings like this:
Item_has_was_updated_May_2010
Item_updated_Apr_2011
Item_got_updated_Sept_2011
I want to iterate through the list of string and update the last 2 parts of the string. The month and the year. The rest of the string I want to remain the same. The month and year will be taken from variables I have set earlier in my script, so let's call the month x and the year y.
My approach is to:
The month and year will be taken from variables I have set earlier in my script, so let's call the month x and the year y.
If anyone can suggest a an approach, it is appreciated.
You can do it without regular expressions by using str.rsplit
:
yourlist = [s.rsplit('_', 2)[0] + '_' + x + '_' + y for s in yourlist]
See it working online: ideone
If you want to use formatting instead of string concatenation, try this:
yourlist = ['{}_{}_{}'.format(s.rsplit('_', 2)[0], x, y) for s in yourlist]
See it working online: ideone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With