class StringReverse(object):
# 1.切片操作
def string_reverse_1(self, s):
return s[::-1]
# 2.转换成list,再reverse,之后重组字符串
def string_reverse_2(self, s):
s_list = list(s)
s_list.reverse()
return "".join(s_list)
# 3.将字符串转换成列表后,交换前后两个字符串的位置,再重组字符串
def string_reverse_3(self, s):
s_list = list(s)
index_begin = 0
index_end = len(s_list)-1
while index_begin < index_end:
s_list[index_begin],s_list[index_end] = s_list[index_end],s_list[index_begin]
index_begin += 1
index_end -= 1
return "".join(s_list)
# 4.利用collections中的双向列表deque,而且deque是线程安全的,可以同时从deque的左右两端提取元素
def string_reverse_4(self, s):
from collections import deque
d = deque()
# 从左边添加元素
d.extendleft(s)
return "".join(d)
d.appendleft("h")
# 从右边添加元素
d.extend(s)
d.append("i")
right = d.pop()
left = d.popleft()
# 5.利用递归
def string_reverse_5(self, s):
if len(s) <= 1:
return s
return self.string_reverse_5(s[1:]) + s[0]
# 6.循环字符串元素
def string_reverse_6(self, s):
return "".join([s[i] for i in range(len(s)-1,-1,-1)])
if __name__ == "__main__":
stringReverse = StringReverse()
s = "abcdefg"
print "string_reverse_1", stringReverse.string_reverse_1(s)
print "string_reverse_2", stringReverse.string_reverse_2(s)
print "string_reverse_3", stringReverse.string_reverse_3(s)
print "string_reverse_4", stringReverse.string_reverse_4(s)
print "string_reverse_5", stringReverse.string_reverse_5(s)
print "string_reverse_6", stringReverse.string_reverse_6(s)
输出结果为:
string_reverse_1 gfedcba
string_reverse_2 gfedcba
string_reverse_3 gfedcba
string_reverse_4 gfedcba
string_reverse_5 gfedcba
string_reverse_6 gfedcba