方法一:直接使用字符串切片功能逆转字符串
#!usr/bin/envpython #encoding:utf-8 defstrReverse(strDemo): returnstrDemo[::-1] print(strReverse('pythontab.com'))
方法二:遍历构造列表法
#!usr/bin/envpython #encoding:utf-8 defstrReverse(strDemo): strList=[] foriinrange(len(strDemo)-1,-1,-1): strList.append(strDemo[i]) return''.join(strList) print(strReverse('pythontab.com'))
方法三:使用reverse函数
#!usr/bin/envpython #encoding:utf-8 defstrReverse(strDemo): strList=list(strDemo) strList.reverse() return''.join(strList) print(strReverse('pythontab.com'))
方法四:借助collections模块方法extendleft
#!usr/bin/envpython #encoding:utf-8 importcollections defstrReverse(strDemo): deque1=collections.deque(strDemo) deque2=collections.deque() fortmpCharindeque1: deque2.extendleft(tmpChar) return''.join(deque2) print(strReverse('pythontab.com'))
方法五:递归实现
#!usr/bin/envpython #encoding:utf-8 defstrReverse(strDemo): iflen(strDemo)<=1: returnstrDemo returnstrDemo[-1]+strReverse(strDemo[:-1]) print(strReverse('pythontab.com'))
#!usr/bin/envpython #encoding:utf-8 defstrReverse(strDemo): strList=list(strDemo) iflen(strList)==0orlen(strList)==1: returnstrList i=0 length=len(strList) whilei<length/2: strList[i],strList[length-i-1]=strList[length-i-1],strList[i] i+=1 return''.join(strList) print(strReverse('pythontab.com'))原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容