Python基礎教程:6種實現字元反轉
阿新 • • 發佈:2021-06-22
將字串s="helloworld"反轉為‘dlrowolleh’
1.切片法最常用
s='helloworld'
r=s[::-1]
print('切片法',r)
#結果
切片法 dlrowolleh
2.使用reduce
from functools import reduce #匿名函式,冒號前面為引數,冒號後為返回結果 #第一步x='h',y='e'返回字串'eh'把這個結果作為新的引數x='eh' y='l' 結果為leh依次類推就把字串反轉了 s='helloworld' r=reduce(lambda x,y:y+x,s) print('reduce函式',r) #結果 reduce函式 dlrowolleh
3.使用遞迴函式
s='helloworld'
def func(s):
if len(s)<1:
return s
return func(s[1:])+s[0]
r=func(s)
print('遞迴函式法',r)
#結果
遞迴函式法 dlrowolleh
4.使用棧
s='helloworld' def func(s): l=list(s) result='' #把字串轉換成列表pop()方法刪除最後一個元素並把該元素作為返回值 while len(l): result=result+l.pop() return result r=func(s) print('使用棧法',r) #結果 使用棧法 dlrowolleh
5.for迴圈
''' Python大型免費公開課,適合初學者入門 加QQ群:579817333 獲取學習資料及必備軟體。 ''' s='helloworld' def func(s): result='' max_index=len(s) #for迴圈通過下標從最後依次返回元素 for index in range(0,max_index): result=result+s[max_index-index-1] return result r=func(s) print('使用for迴圈法',r) #結果 使用for迴圈法 dlrowolleh
6.使用列表reverse法
s='helloworld'
l=list(s)
#reverse方法把列表反向排列
l.reverse()
#join方法把列表組合成字串
r="".join(l)
print('使用列表reverse法',r)
#結果
使用列表reverse法 dlrowolleh