python反轉(zhuǎn)(逆序)字符串的6種方法詳細
對于一個給定的字符串,逆序輸出,這個任務對于python來說是一種很簡單的操作,畢竟強大的列表和字符串處理的一些列函數(shù)足以應付這些問題 了,今天總結(jié)了一下python中對于字符串的逆序輸出的幾種常用的方法
方法一:直接使用字符串切片功能逆轉(zhuǎn)字符串
>>> def strReverse(strDemo):
return strDemo[::-1]
>>> print(strReverse('jb51.net'))
ten.15bj
結(jié)果:
ten.15bj
方法二:遍歷構(gòu)造列表法
循環(huán)遍歷字符串, 構(gòu)造列表,從后往前添加元素, 最后把列表變?yōu)樽址?/p>
>>> def strReverse(strDemo):
strList=[]
for i in range(len(strDemo)-1, -1, -1):
strList.append(strDemo[i])
return ''.join(strList)
>>> print(strReverse('jb51.net'))
ten.15bj
結(jié)果:
ten.15bj
方法三:使用reverse函數(shù)
將字符串轉(zhuǎn)換為列表使用reverse函數(shù)
>>> def strReverse(strDemo):
strList = list(strDemo)
strList.reverse()
return ''.join(strList)
>>> print(strReverse('jb51.net'))
ten.15bj
結(jié)果:
ten.15bj
方法四:借助collections模塊方法extendleft
>>> import collections
>>> def strReverse(strDemo):
deque1=collections.deque(strDemo)
deque2=collections.deque()
for tmpChar in deque1:
deque2.extendleft(tmpChar)
return ''.join(deque2)
>>> print(strReverse('jb51.net'))
ten.15bj
結(jié)果:
ten.15bj
方法五:遞歸實現(xiàn)
>>> def strReverse(strDemo):
if len(strDemo)<=1:
return strDemo
return strDemo[-1]+strReverse(strDemo[:-1])
>>> print(strReverse('jb51.net'))
ten.15bj
結(jié)果:
ten.15bj
方法六:借助基本的Swap操作,以中間為基準交換對稱位置的字符
>>> 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:
strList[i], strList[length-i-1]=strList[length-i-1], strList[i]
i+=1
return ''.join(strList)
>>> print(strReverse('jb51.net'))
ten.15bj
結(jié)果:
ten.15bj
本文講解的python反轉(zhuǎn)(逆序)字符串的6種方法詳細請到這里,更多關于python反轉(zhuǎn)(逆序)字符串的方法請查看下面的相關鏈接
相關文章
Python Pydantic進行數(shù)據(jù)驗證的方法詳解
在 Python 中,有許多庫可用于數(shù)據(jù)驗證和處理,其中一個流行的選擇是 Pydantic,下面就跟隨小編一起學習一下Pydantic 的基本概念和用法吧2024-01-01
Python實現(xiàn)PIL圖像處理庫繪制國際象棋棋盤
本文主要介紹了Python實現(xiàn)PIL圖像處理庫繪制國際象棋棋盤,文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學習學習吧2021-07-07
python基礎入門詳解(文件輸入/輸出 內(nèi)建類型 字典操作使用方法)
這篇文章主要介紹了python基礎入門,包括文件輸入/輸出、內(nèi)建類型、字典操作等使用方法2013-12-12
pandas中按行或列的值對數(shù)據(jù)排序的實現(xiàn)
本文主要介紹了pandas中按行或列的值對數(shù)據(jù)排序的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02
Python內(nèi)置函數(shù)hex()的實現(xiàn)示例
這篇文章主要介紹了Python內(nèi)置函數(shù)hex()的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08

