python中列表的强大解析功能使字符串的翻转变得易如反掌,下面介绍几种方法:
1,使用字符串分片
>>>s = 'python'
>>>s[::-1]
'nohtyp'
2,将字符串转换成列表,使用列表的reverse方法,这里reverse是原地翻转,返回值是None,''.join(s)是将列表转换成字符串
>>>s = list(s)
>>>s.reverse()
>>>''.join(s)
'nohtyp'
3,使用for循环,从右到左输出
>>>s= ''.join(s[i] for i in range(len(s)-1,-1,-1))
>>>s
'nohtyp'
4,字母位置原地对调
>>>s = list(s)
>>>for i,j in zip(range(len(s)-1, 0, -1), range(len(s)//2)):
s[i], s[j] = s[j], s[i]
>>> ''.join(s)
'nohtyp'
5,递归方式,每次输出一个字符串
>>>def s_r(s):
if len(s) <= 1:
return s
return s_r(s[1:]) + s[0]
>>>s_r(s)
'nohtyp'
6,双端队列,使用extendleft()函数
>>>from collections import deque
>>>d = deque()
>>>d.extendleft(s)
>>>''.join(d)
'nohtyp'
来源:csdn 作者:Spike_King