简体   繁体   English

如何在Python中使用正则表达式替换字符串

[英]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[az]*', '03')

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

Could someone please help me and tell me what I'm doing wrong. 有人可以帮助我,告诉我我做错了什么。

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. 当然,您也可以使用for循环以提高可读性。

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

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'] s3现在包含['03/21/2019', '03/23/2019']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM