输入:string_reverse('abcdef'),返回:'fedcba',写出你能想到的多种方法
1.使用字符串本身的翻转
def string_reverse1(text='abcdef'):
... return text[::-1]
2.把字符串变为列表,用列表的reverse函数
>>> def string_reverse2(text='abcdef'):
... new_text=list(text)
... new_text.reverse()
... return ''.join(new_text)
...
>>> print string_reverse2('abcdef')
fedcba
3.新建一个列表,从后往前取
>>> def string_reverse3(text='abcdef'):
... new_text=[]
... for i in range(1,len(text)+1):
... new_text.append(text[-i])
... return ''.join(new_text)
...
>>> print string_reverse3('abcdef')
fedcba
4.利用双向列表deque中的extendleft函数
>>> from collections import deque
>>> def string_reverse4(text='abcdef'):
... d = deque()
... d.extendleft(text)
... return ''.join(d)
...
>>> print string_reverse4('abcdef')
fedcba
5.递归
>>> def string_reverse5(text='abcdef'):
... if len(text)<=1:
... return text
... else:
... return string_reverse5(text[1:]+text[0])
...
>>> print string_reverse5('abcdef')