Python中逆序输出字符串的六种方法
方法一:直接使用字符串切片功能逆转字符串
#!usr/bin/env python# encoding:utf-8
def strReverse(strDemo):
return strDemo[::-1]
print(strReverse('pythontab.com'))
方法二:遍历构造列表法
#!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'))
方法三:使用reverse函数
#!usr/bin/env python# encoding:utf-8
def strReverse(strDemo):
strList = list(strDemo)
strList.reverse()
return ''.join(strList)
print(strReverse('pythontab.com'))
方法四:借助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'))
方法五:递归实现
#!usr/bin/env python# encoding:utf-8
def strReverse(strDemo):
if len(strDemo)<=1:
return strDemo
return strDemo[-1]+strReverse(strDemo[:-1])
print(strReverse('pythontab.com'))
方法六:借助基本的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:
strList[i], strList[length-i-1]=strList[length-i-1], strList[i]
i+=1
return ''.join(strList)
print(strReverse('pythontab.com'))
以上是 Python中逆序输出字符串的六种方法 的全部内容, 来源链接: utcz.com/z/527879.html