Python字符串反转方法小记

有个朋友开突然问我在Python下怎么把字符串倒过来排序,刚开始我懵逼了,倒过来排序有什么意义,你的场景是什么,如果你单纯问我这个作为一个小考验,我觉得搜索一大推,自行Google就好啊。他说他们需要针对密码加密,简单的逻辑就是反转加密实现,厉害了疙瘩。下面我主要记录一下Python下的几种方法。

No.1 切片方式

字符串的切片跟列表是一样的,主要是利用切片的扩展语法-1来实现
def rev1(cont):
	return cont[::-1]
切片详细语法查看:https://docs.python.org/2/whatsnew/2.3.html#extended-slices 

No.2 列表reverse实现

利用列表的reverse()方法这个特性,可以先将字符串转换成列表,利用reverse()方法进行反转后,再处理成字符串。
def rev2(cont):
	result = list(cont)
	result.reverse()
	return ''.join(result)

No.3 内置函数reversed实现

def rev3(cont):
	return ''.join(reversed(cont))

No.4 递归方法

def rev4(cont):
	if cont == "":
		return cont
	else:
		return rev4(cont[1:])+cont[0]
# 在Python 3里,reduce()内置函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里
from functools import reduce 

def rev5(cont):
	return reduce(lambda x, y : y + x, cont)

No.5 字符串拼接

def rev6(cont):
	new_string = ''
	index = len(cont)
	while index:
		index -= 1                    # index = index - 1
		new_string += cont[index]     # new_string = new_string + character
	return new_string
def rev7(cont):
	new_strings = 
	index = len(cont)
	while index:
		index -= 1                       
		new_strings.append(cont[index])
	return ''.join(new_strings)
如上几种方法效率比较:
#!/usr/bin/env python3
# Author: nock
from functools import reduce
import timeit

cont = 'kcon' * 20

def rev1(cont):
	return cont[::-1]
	
def rev2(cont):
	result = list(cont)
	result.reverse()
	return ''.join(result)

def rev3(cont):
	return ''.join(reversed(cont))
	
def rev4(cont):
	if cont == "":
		return cont
	else:
		return rev4(cont[1:])+cont[0]

def rev5(cont):
	return reduce(lambda x, y : y + x, cont)

def rev6(cont):
	new_string = ''
	index = len(cont)
	while index:
		index -= 1                    # index = index - 1
		new_string += cont[index]     # new_string = new_string + character
	return new_string

def rev7(cont):
	new_strings = 
	index = len(cont)
	while index:
		index -= 1                       
		new_strings.append(cont[index])
	return ''.join(new_strings)

if __name__ == '__main__':		
    print("rev1 run time is: %s" % min(timeit.repeat(lambda: rev1(cont))))
    print("rev2 run time is: %s" % min(timeit.repeat(lambda: rev2(cont))))
    print("rev3 run time is: %s" % min(timeit.repeat(lambda: rev3(cont))))
    print("rev4 run time is: %s" % min(timeit.repeat(lambda: rev4(cont))))
    print("rev5 run time is: %s" % min(timeit.repeat(lambda: rev5(cont))))
    print("rev6 run time is: %s" % min(timeit.repeat(lambda: rev6(cont))))
    print("rev7 run time is: %s" % min(timeit.repeat(lambda: rev7(cont))))
时间结果如下:
rev1 run time is: 0.45436444599181414
rev2 run time is: 2.3974227079888806
rev3 run time is: 2.633627591014374
rev4 run time is: 3.0160443240310997
rev5 run time is: 16.342944753996562
rev6 run time is: 12.666344199969899
rev7 run time is: 14.762871471000835
所以如上可以看出,还是用切片的方法最好,所以记住切片步长为-1就可反转就好。

1 个评论

可以参考stackoverflow上的回答:http://stackoverflow.com/questions/931092/reverse-a-string-in-python

要回复文章请先登录注册