zoukankan      html  css  js  c++  java
  • Python基础教程:6种实现字符反转

    将字符串s="helloworld"反转为‘dlrowolleh’ 

    1.切片法最常用

    s='helloworld'
    r=s[::-1]
    print('切片法',r)
    
    #结果
    切片法 dlrowolleh
    

    2.使用reduce

    from functools import reduce
    #匿名函数,冒号前面为参数,冒号后为返回结果
    #第一步x='h',y='e'返回字符串'eh'把这个结果作为新的参数x='eh' y='l' 结果为leh依次类推就把字符串反转了
    s='helloworld'
    r=reduce(lambda x,y:y+x,s)
    print('reduce函数',r)
    
    #结果
    reduce函数 dlrowolleh
    

    3.使用递归函数

    s='helloworld'
    def func(s):
        if len(s)<1:
            return s
        return func(s[1:])+s[0]
     
    r=func(s)
    print('递归函数法',r)
    
    #结果
    递归函数法 dlrowolleh
    

    4.使用栈

    s='helloworld'
    def func(s):
        l=list(s)
        result=''
        #把字符串转换成列表pop()方法删除最后一个元素并把该元素作为返回值
        while len(l):
            result=result+l.pop()
        return result
     
    r=func(s)
    print('使用栈法',r)
    
    #结果
    使用栈法 dlrowolleh
    

    5.for循环

    '''
    Python大型免费公开课,适合初学者入门
    加QQ群:579817333 获取学习资料及必备软件。
    '''
    s='helloworld'
    def func(s):
        result=''
        max_index=len(s)
        #for循环通过下标从最后依次返回元素
        for index in range(0,max_index):
            result=result+s[max_index-index-1]
        return result
     
    r=func(s)
    print('使用for循环法',r)
    
    #结果
    使用for循环法 dlrowolleh
    

    6.使用列表reverse法

    s='helloworld'
    l=list(s)
    #reverse方法把列表反向排列
    l.reverse()
    #join方法把列表组合成字符串
    r="".join(l)
    print('使用列表reverse法',r)
    
    #结果
    使用列表reverse法 dlrowolleh
    
  • 相关阅读:
    卸载了PL/SQL Developer,说一下与Toad for Oracle的对照
    列举游戏开发过程中的一些不良现象
    vue23:vue-loader
    vue22 路由
    vue21 slot占位
    vue20 父子组件数据交互
    vue19 组建 Vue.extend component、组件模版、动态组件
    vue18 动画
    vue17 $watch 监听数据变化
    vue16 自定义键盘属性
  • 原文地址:https://www.cnblogs.com/xxpythonxx/p/14920065.html
Copyright © 2011-2022 走看看