您好,欢迎访问一九零五行业门户网

python如何对指定字符串逆序

python对指定字符串逆序的方法:1、:直接使用字符串切片功能逆转字符串;2、遍历构造列表法;3、使用reverse函数实现;4、借助collections模块方法extendleft;5、使用递归实现。
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('pythontab.com'))
结果:
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: strlist[i], strlist[length-i-1]=strlist[length-i-1], strlist[i] i+=1 return ''.join(strlist) print(strreverse('pythontab.com'))
结果:
moc.batnohtyp
相关免费学习推荐:python视频教程
以上就是python如何对指定字符串逆序的详细内容。
其它类似信息

推荐信息