如何在Python中将字符串中的所有DD/MM/YYYY更改为MM/DD/YYYY格式

2024-03-29 10:39:16 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

您可以通过re模块和一个替换函数来实现这一点。你知道吗

import re

# make the re pattern object
# it looks for the following pattern: 2 digits / 2 digits / 4 digits
date_pattern = re.compile(r'\d{2}/\d{2}/\d{4}')

# make the replacement function to be called to replace matches
# takes the match object, splits the date up and swaps the first two elements
def swap_date_arrangement(date_string):
    return_string = date_string.group(0).split('/')
    return_string[0], return_string[1] = return_string[1], return_string[0]
    return '/'.join(return_string)

# test the solution...
input_string = "I graduated on 09/08/2016 and joined PHD on 01/07/2017 then since 25/10/2011 I work on..."

# assign the new string
replaced_string = re.sub(date_pattern, swap_date_arrangement, input_string)

print replaced_string

可以使用^{}查找和替换所有日期:

>>> import re
>>> s = 'I graduated on 09/08/2016 and joined PHD on 01/07/2017 then since 25/10/2011 I works on'
>>> re.sub(r'(\d{2})/(\d{2})/(\d{4})', r'\2/\1/\3', s)
'I graduated on 08/09/2016 and joined PHD on 07/01/2017 then since 10/25/2011 I works on'

上面将捕获模式dd/dd/dddd的所有出现,其中d是三个不同组的数字。然后它将只输出一个字符串,其中第一组和第二组已交换。你知道吗

相关问题 更多 >