最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

python如何对指定字符串逆序

来源:动视网 责编:小采 时间:2020-11-02 18:01:52
文档

python如何对指定字符串逆序

python如何对指定字符串逆序:python对指定字符串逆序的方法:1、:直接使用字符串切片功能逆转字符串;2、遍历构造列表法;3、使用reverse函数实现;4、借助collections模块方法extendleft;5、使用递归实现。python对指定字符串逆序的方法:方法一:直接使用字符串切片功能逆转字符串
推荐度:
导读python如何对指定字符串逆序:python对指定字符串逆序的方法:1、:直接使用字符串切片功能逆转字符串;2、遍历构造列表法;3、使用reverse函数实现;4、借助collections模块方法extendleft;5、使用递归实现。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: s
trList[i], strList[length-i-1]=strList[length-i-1], strList[i] i+=1 
 return ''.join(strList) 
print(strReverse('pythontab.com'))

结果:

moc.batnohtyp

相关免费学习推荐:python视频教程

文档

python如何对指定字符串逆序

python如何对指定字符串逆序:python对指定字符串逆序的方法:1、:直接使用字符串切片功能逆转字符串;2、遍历构造列表法;3、使用reverse函数实现;4、借助collections模块方法extendleft;5、使用递归实现。python对指定字符串逆序的方法:方法一:直接使用字符串切片功能逆转字符串
推荐度:
标签: 某个 字符串 python
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top