首页 > IT职业 > IT职场 > python对指定字符串逆序的6种方法
对于一个给定的字符串,逆序输出,这个任务对于python来说是一种很简单的操作,毕竟强大的列表和字符串处理的一些列函数足以应付这些问题 了,今天总结了一下python中对于字符串的逆序输出的几种常用的方法
| 12345 |
#!usr/bin/env python # encoding:utf-8 def strReverse(strDemo): return strDemo[::-1] print(strReverse('pythontab.com'))
|
结果:
| 1 | moc.batnohtyp |
循环遍历字符串, 构造列表,从后往前添加元素, 最后把列表变为字符串
| 12345678 |
#!usr/bin/env python # encoding:utf-8 def strReverse(strDemo): strList=[] for i in range(len(strDemo)-1, -1, -1): strList.append(strDemo[i]) return ''.join(strList) print(strReverse('pythontab.com'))
|
结果:
| 1 | moc.batnohtyp |
将字符串转换为列表使用reverse函数
| 1234567 |
#!usr/bin/env python # encoding:utf-8 def strReverse(strDemo): strList = list(strDemo) strList.reverse() return ''.join(strList) print(strReverse('pythontab.com'))
|
结果:
| 1 | moc.batnohtyp |
| 12345678910 |
#!usr/bin/env python # encoding:utf-8 import collections def strReverse(strDemo): deque1=collections.deque(strDemo) deque2=collections.deque() for tmpChar in deque1: deque2.extendleft(tmpChar) return ''.join(deque2) print(strReverse('pythontab.com'))
|
结果:
| 1 | moc.batnohtyp |
| 1234567 |
#!usr/bin/env python # encoding:utf-8 def strReverse(strDemo): if len(strDemo)
|
结果:
| 1 | moc.batnohtyp |
| 1234567891011121314 |
#!usr/bin/env python #encoding:utf-8 def strReverse(strDemo): strList=list(strDemo) if len(strList)==0 or len(strList)==1: return strList i=0 length=len(strList) while i
|
结果:
| 1 | moc.batnohtyp |
原文来源:https://www.pythontab.com/html/2018/pythonjichu_0426/1283.html
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1817/viewspace-2811434/ ,如需转载,请注明出处,否则将追究法律责任。