Python中逆序输出字符串的六种方法

图片[1]-Python中逆序输出字符串的六种方法-uusu优素-乐高,模型,3d打印,编程

方法一:直接使用字符串切片功能逆转字符串

#!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
喜欢就支持一下吧
点赞12 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容