Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中将字符串中的所有DD/MM/YYYY更改为MM/DD/YYYY格式_Python_Python 2.7 - Fatal编程技术网

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

如何在Python中将字符串中的所有DD/MM/YYYY更改为MM/DD/YYYY格式,python,python-2.7,Python,Python 2.7,如何将字符串中的所有DD/MM/YYYY更改为MM/DD/YYYY格式 输入字符串:我于2016年8月9日毕业,并于2017年7月1日加入博士学位,然后自2011年10月25日起我在 到 输出字符串:我于2016年9月8日毕业,并于2017年1月7日加入博士学位,然后自2011年10月25日起,我从事于您可以使用查找和替换所有日期事件: >>> import re >>> s = 'I graduated on 09/08/2016 and joined PH

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

输入字符串:我于2016年8月9日毕业,并于2017年7月1日加入博士学位,然后自2011年10月25日起我在

输出字符串:我于2016年9月8日毕业,并于2017年1月7日加入博士学位,然后自2011年10月25日起,我从事于

您可以使用查找和替换所有日期事件:

>>> 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
是三个不同组的数字。然后,它将只输出一个字符串,其中第一组和第二组已交换。

您可以使用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

啊,我更喜欢你的。我不知道你能这么容易地提到抓捕小组。很高兴学到一些东西仍然发布我的解决方案,因为我已经做了几分钟了。