首頁  >  文章  >  後端開發  >  python如何對指定字串逆序

python如何對指定字串逆序

coldplay.xixi
coldplay.xixi原創
2020-10-21 15:01:2125288瀏覽

python對指定字串逆序的方法:1、:直接使用字串切片功能逆轉字串;2、遍歷建構列表法;3、使用reverse函數實作;4、借助collections模組方法extendleft; 5.使用遞迴實作。

python如何對指定字串逆序

python對指定字串逆序的方法:

方法一:直接使用字串切片函數逆轉字串

 #!usr/bin/env python  
# encoding:utf-8  
def strReverse(strDemo):   
return strDemo[::-1]  
print(strReverse('pythontab.com'))

結果:

moc.batnohtyp

方法二:遍歷建構列表法

#循環遍歷字串, 建構列表,從後往前加入元素, 最後把列表變成字串

#!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'))

結果:

moc.batnohtyp

方法三:使用reverse函數

將字串轉換成列表使用reverse函數

#!usr/bin/env python  
# encoding:utf-8  
def strReverse(strDemo):    
strList = list(strDemo)    
strList.reverse()    
return ''.join(strList) 
print(strReverse('pythontab.com'))

結果:

##moc.batnohtyp

#方法四:借助collections模組方法extendleft

#!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'))

結果:

moc.batnohtyp

方法五:遞歸實作

#!usr/bin/env python  
# encoding:utf-8  
def strReverse(strDemo):    if len(strDemo)<=1:      
return strDemo   
 return strDemo[-1]+strReverse(strDemo[:-1])  
print(strReverse(&#39;pythontab.com&#39;))

結果:

moc.batnohtyp

#方法六:借助基本的Swap操作,以中間為基準交換對稱位置的字元#

 #!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 < length/2:      s
trList[i], strList[length-i-1]=strList[length-i-1], strList[i]      i+=1 
 return &#39;&#39;.join(strList) 
print(strReverse(&#39;pythontab.com&#39;))

結果:

moc.batnohtyp


#相關免費學習推薦:python影片教學

#

以上是python如何對指定字串逆序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn