反转字符串的顺序,同时保留字符串的原始内容

时间:2013-07-06 04:37:23

标签: python string reverse

所以我正在尝试将字符串31/12/9999转换为9999/12/31,我一直在尝试date = date[::-1],但它会生成9999/21/31并且不会保留php的内容字符串。

我正在寻找类似于reverse_array( $array , $preserve );,{{1}}的内容。

2 个答案:

答案 0 :(得分:5)

这是使用Python

的方法
 '/'.join(reversed(s.split('/')))
 9999/12/31

答案 1 :(得分:4)

将其拆分为包含str.split()的列表,然后使用str.join()打印反向字符串:

>>> s = "31/12/9999"
>>> L = s.split('/') # L now contains ['31', '12', '9999']
>>> print '/'.join(L[::-1]) # Reverse the list, then print all the content in the list joined by a /
9999/12/31

或者,在一行中:

>>> print '/'.join(s.split('/')[::-1])

但是,如果您正在处理日期,则应使用datetime模块,以便稍后可以使用日期执行其他操作:

>>> import datetime
>>> s = "31/12/9999"
>>> date = datetime.datetime.strptime(s, '%d/%m/%Y')
>>> print date.strftime('%Y/%m/%d')
9999/12/31

时间比较:

$ python -m timeit 's = "31/12/9999"' "'/'.join(s.split('/')[::-1])"
1000000 loops, best of 3: 0.799 usec per loop
$ python -m timeit 's = "31/12/9999"' "'/'.join(reversed(s.split('/')))"
1000000 loops, best of 3: 1.53 usec per loop