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
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
相关文章推荐
- 零基础学python-18.9 序列映射函数:map
- 零基础学python-18.9 序列映射函数:map
- cmd中运行python文件,并带参数
- Python 16进制与字符串的转换
- python正则表达式匹配邮箱
- python 实现重启路由器
- 计划看一本英文版的Python基础教程
- kNN算法python代码学习2-手写识别系统
- python启动浏览器崩溃
- 【干货】前方高能!如何保障Python应用的高性能
- Python list(列表)实践
- Autorun a python script after reboot using rc.local
- 小甲鱼Python笔记(类)
- 【干货】前方高能!如何保障Python应用的高性能
- 【干货】前方高能!如何保障Python应用的高性能
- Python 3.5发布:新增模块,性能优化,对开发者更友好
- Ubuntu下安装python的torndb开发环境
- python例子-抓取网站IP列表
- Python博客
- python 字符串编程技巧