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'
您可以通过re模块和一个替换函数来实现这一点。你知道吗
可以使用^{} 查找和替换所有日期:
上面将捕获模式
dd/dd/dddd
的所有出现,其中d
是三个不同组的数字。然后它将只输出一个字符串,其中第一组和第二组已交换。你知道吗相关问题 更多 >
编程相关推荐