• 技术文章 >后端开发 >Python教程

    python如何对指定字符串逆序

    coldplay.xixicoldplay.xixi2020-10-21 15:01:21原创13612

    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如何对指定字符串逆序的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:python 字符串逆序
    上一篇:python如何输入十个学生的成绩 下一篇:python如何实现网络爬虫
    Web大前端开发直播班

    相关文章推荐

    • python入口函数是什么• Python if有多个条件怎么办• python必背内容有哪些• python如何输入十个学生的成绩

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网