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 tried a few things, but none work:

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

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

4
  • 9
    If you're only working with dates I think you're better off using a datetime: stackoverflow.com/questions/2265357/… Commented Apr 8, 2019 at 20:10
  • 4
    replace isn't using regexes. You need re.sub(r'Mar[a-z]*', '03',s3[i]) Commented Apr 8, 2019 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. Commented Apr 8, 2019 at 20:11
  • This question is similar to: How to input a regex in string.replace?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jun 12 at 4:43

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.