shellym
shellym

Reputation: 576

How to replace string using regular expression in Python

I need help with replacing characters in a string using regular expressions.

Input :

s3 = ['March/21/2019' , 'Mar/23/2019']

Desired Output :

s3 = ['03/21/2019' , '03/23/2019']

I've tried a few things, but none of them seem to make any impact on the input:

  1. s3[i] = s3[i].replace(r'Mar[a-z]*', '03')

  2. s3[i] = s3[i].replace(r'(?:Mar[a-z]*)', '03')

Could someone please help me and tell me what I'm doing wrong.

Upvotes: 2

Views: 5484

Answers (2)

McGlothlin
McGlothlin

Reputation: 2099

If you're only working with dates, try something like this:

import datetime

s3 = ['March/21/2019' , 'Mar/23/2019']

for i in range(0, len(s3)):
    try:
        newformat = datetime.datetime.strptime(s3[i], '%B/%d/%Y')
    except ValueError:
        newformat = datetime.datetime.strptime(s3[i], '%b/%d/%Y')

    s3[i] = newformat.strftime('%m/%d/%Y')

s3 now contains ['03/21/2019', '03/23/2019']

Upvotes: 1

schilli
schilli

Reputation: 1838

This works.

import re
s3 = ['March/21/2019' , 'Mar/23/2019']
s3 = [re.sub(r'Mar[a-z]*', '03', item) for item in s3]

# ['03/21/2019', '03/23/2019']

Of course, you can also use a for loop for better readability.

import re
s3 = ['March/21/2019' , 'Mar/23/2019']
for i in range(len(s3)):
    s3[i] = re.sub(r'Mar[a-z]*', '03', s3[i])

# ['03/21/2019', '03/23/2019']

Upvotes: 5

Related Questions