python对指定字符串逆序的6种方法

对于一个给定的字符串,逆序输出,这个任务对于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('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

  • 初学者学习python2还是python3?
  • python获取本机IP、mac地址、计算机名
  • 详解python2 和 python3的区别
  • python基础之删除文件及删除目录的方法
  • 用python求第1000个质数的值
  • python常用函数年初大总结
  • Python3 - 时间处理与定时任务
  • Python开发的CMS系统,Silva CMS 3 发布
  • python基础之使用os.system来执行系统命令
  • 判断python字典中key是否存在的两种方法
  • 初学者学习python2还是python3?
  • python基础之删除文件及删除目录的方法
  • python获取本机IP、mac地址、计算机名
  • python获取系统时间(时间函数详解)
  • 详解python2 和 python3的区别
  • 用python求第1000个质数的值
  • Python3 - 时间处理与定时任务
  • 命令行看糗百
  • Python算法之---冒泡,选择,插入排序算法
  • python 中求和函数 sum详解
  • range方法在Python2和Python3中的不同
  • python3 数组(列表)初始化
  • 记一次crontab中date命令错用导致的问题
  • MySQL用LIKE特殊字符搜索
  • CentOS 7 下修改主机名
  • Python3正则表达式之:(?(id/name)y...
  • TIOBE编程语言排行榜2019年 Python稳居前三
  • 解压命令unzip常用方法汇总
  • 解析redis备份文件rdb的两种方法及对比
  • 百度视觉语义化平台2.0:交互升级和...
  • 5G时代的视觉语义化技术:软硬结合...
  • 百度AutoDL重磅升级至3.0:设计、迁...