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

对于一个给定的字符串,逆序输出,这个任务对于python来说是一种很简单的操作,毕竟强大的列表和字符串处理的一些列函数足以应付这些问题 了,今天总结了一下python中对于字符串的逆序输出的几种常用的方法


方法一:直接使用字符串切片功能逆转字符串

1
2
3
4
5
#!usr/bin/env python 
# encoding:utf-8 
def strReverse(strDemo):
  return strDemo[::-1] 
print(strReverse('pythontab.com'))


结果:

1
moc.batnohtyp


方法二:遍历构造列表法

循环遍历字符串, 构造列表,从后往前添加元素, 最后把列表变为字符串

1
2
3
4
5
6
7
8
#!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'))

结果:

1
moc.batnohtyp


方法三:使用reverse函数

将字符串转换为列表使用reverse函数

1
2
3
4
5
6
7
#!usr/bin/env python 
# encoding:utf-8 
def strReverse(strDemo): 
  strList = list(strDemo) 
  strList.reverse() 
  return ''.join(strList)
print(strReverse('pythontab.com'))


结果:

1
moc.batnohtyp


方法四:借助collections模块方法extendleft

1
2
3
4
5
6
7
8
9
10
#!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'))


结果:

1
moc.batnohtyp


方法五:递归实现

1
2
3
4
5
6
7
#!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'))


结果:

1
moc.batnohtyp


方法六:借助基本的Swap操作,以中间为基准交换对称位置的字符

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

相关文章阅读

  • python对字典的基本操作(遍历、排序)总结,字典遍历 python
  • ,,python对一个数向上取整的实例方法
  • python把excel数据对比,python对比excel重复数据
  • golang python对比,go语言和python对比
  • 让python读的文件应该放在哪,python对文件的读写操作方式
  • python中字符串可以进行切片赋值吗,python对字符串切片
  • python对字符串数组进行排序,依据字符数,字符串排列组合python
  • python对数组进行排序,python分组排序提取每组前10%
  • python对excel数据处理,python处理excel教程
  • python读取文件字节长度,python对文件内每个字符进行大小写转换处理并输出
  • python对比c语言的优势,python好学还是c语言好学
  • python读文件和写文件,python对文件进行读写操作
  • 下列关于python的描述错误的是,python对于函数的定义错误的是
  • python对csv文件处理,python读取csv文件代码
  • python对某一列数据排序,python中给列表排序
  • 留言与评论(共有 条评论)
    昵称:
    匿名发表 登录账号
             
       
    验证码: