您的位置:首页 > 编程语言 > Python开发

python中翻转字符串的方法,标记一下

2015-09-21 17:18 351 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: