2

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.

shellym
  • 546
  • 1
  • 5
  • 11
  • 9
    If you're only working with dates I think you're better off using a `datetime`: https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format – McGlothlin Apr 08 '19 at 20:10
  • 3
    `replace` isn't using regexes. You need `re.sub(r'Mar[a-z]*', '03',s3[i])` – Jean-François Fabre Apr 08 '19 at 20:10
  • If you want to use regex, you need to import it via `import re` and use it instead of `str.replace()`, which doesn't support regex patterns. _If_ your data list is part of a pandas dataframe though, you could use `df.str.replace()`, which in turn supports them. – SpghttCd Apr 08 '19 at 20:11

2 Answers2

5

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']
schilli
  • 1,700
  • 1
  • 9
  • 17
0

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']

McGlothlin
  • 2,059
  • 1
  • 15
  • 28