zoukankan      html  css  js  c++  java
  • 逆转字符串—输入一个字符串,将其逆转并输出。

    实现Python字符串反转有4种方法:

    1、列表的方式:

    def rev(s):
        a = list(s)
        a.reverse()
        return (''.join(a))
    a = rev('huowuzhao')
    print (a)
    
    ---------------------------------------------------------------------------------
    C:UsersAdministratorAppDataLocalProgramsPythonPython35python.exe D:/pycharm/hello.py
    oahzuwouh
    Process finished with exit code 0

    这种方法是采用列表的reverse方法,先将s转换为列表,然后通过reverse方法反转,然后在通过join连接为字符串。

    reverse是把列表方向排序;

    2、切片的方式:

    *切片的方式最简洁

    def rev(s):
        return (s[::-1])
    a = rev('huowuzhao')
    print (a)
    
    ---------------------------------------------------------------------------
    
    C:UsersAdministratorAppDataLocalProgramsPythonPython35python.exe D:/pycharm/hello.py
    oahzuwouh
    

    这是采用切片的方法,设置步长为-1,也就是反过来排序。
    这种方法是最简洁的,也是最推荐的。

    3、reduce:

    from functools import reduce  #因为我是用的是Python3.5,所以reduce函数需要引入
    def rev(s):
        return reduce(lambda x, y : y + x, s)
    a = rev('huowuzhao')
    print (a)
    
    -----------------------------------------------------------------------------------------
    
    C:UsersAdministratorAppDataLocalProgramsPythonPython35python.exe D:/pycharm/hello.py
    oahzuwouh
    

    4、还有一种类似切片的方法,不过稍微较前几种稍微复杂点:

    def rev(s):
        str0 = ''
        l = len(s)-1
        while l >= 0:
           str0 += s[l]
           l -= 1
        return (str0)
    a = rev('huowuzhao')
    print (a)
    
    ---------------------------------------------------------------------------------
    
    C:UsersAdministratorAppDataLocalProgramsPythonPython35python.exe D:/pycharm/hello.py
    oahzuwouh
    

    这种方法是先设置一个str0的空变量,然后在s中从后往前取值,然后追加到str0中。

     

  • 相关阅读:
    Flume
    nodejs中npm工具自身升级
    Nodejs v4.x.0API文档学习(1)简介
    nodejs设置NODE_ENV环境变量(1)
    nodejs使用express4框架默认app.js配置说明
    mongodb2.X添加权限
    javascript中new Date浏览器兼容性处理
    Android Studio中文组(中文社区)
    Javascript日期处理类库Moment.js
    android 按两次返回键退出应用
  • 原文地址:https://www.cnblogs.com/pythonal/p/5940982.html
Copyright © 2011-2022 走看看