zoukankan      html  css  js  c++  java
  • python3反转字符串的3种方法

    前段时间看到letcode上的元音字母字符串反转的题目,今天来研究一下字符串反转的内容。主要有三种方法:

    1.切片法(最简洁的一种)
    #切片法
    def reverse1():
        s=input("请输入需要反转的内容:")
        return s[::-1]
    reverse1()
    
    #运行结果
    In [23]: def reverse1():
        ...: s=input("请输入需要反转的内容:")
        ...: return s[::-1]
        ...: 
        ...: reverse1()
    
    请输入需要反转的内容:你是一个小南瓜
    Out[23]: '瓜南小个一是你'
    

    参考stackflow上的答案
    原理是:This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.

    2.递归
    #递归反转
    def reverse2(s):
        if s=="":
            return s
        else:
            return reverse2(s[1:])+s[0]
    reverse2("sidfmawsmdisd是当面问")
    
    #运行结果
    In [24]: def reverse2(s):
        ...: if s=="":
        ...: return s
        ...: else:
        ...: return reverse2(s[1:])+s[0]
        ...: 
        ...: reverse2("sidfmawsmdisd是当面问")
    Out[24]: '问面当是dsidmswamfdis'
    
    3.借用列表,使用reverse()方法

    Python中自带reverse()函数,可以处理列表的反转,来看示例:

    In [25]: l=['a', 'b', 'c', 'd']
        ...: l.reverse()
        ...: print (l)
    ['d', 'c', 'b', 'a']
    

    reverse()函数将列表的内容进行了反转,借助这个特性,可以先将字符串转换成列表,利用reverse()函数进行反转后,再处理成字符串。

    #借用列表,使用reverse()方法
    def reverse3(s):
        l=list(s)
        l.reverse()
        print("".join(l))
    reverse3("soifmi34pomOsprey,,是")
    
    #运行结果
    In [26]: def reverse3(s):
        ...: l=list(s)
        ...: l.reverse()
        ...: print("".join(l))
        ...: 
        ...: reverse3("soifmi34pomOsprey,,是")
        ...: 
    是,,yerpsOmop43imfios
    

    今天的学习就到这里。贴上letcode上元音字母反转的地址,待后续研究。



    作者:3230
    链接:https://www.jianshu.com/p/c61279736a03
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    axis2 WebService的发布与调用
    sql语句having子句用法,很多时候你曾忘掉
    linux下tomcat开机自启动
    框架使用的技术主要是SpringMVC 在此基础上进行扩展
    SpringMVC整合Mongodb开发 架构搭建
    解决Linux下3T硬盘分区只有2T(2199G)可用
    ubuntu cp(copy) command
    Linux如何根据UUID自动挂载磁盘分区
    python exec和eval
    在OpenERP报表中使用selection 类型字段
  • 原文地址:https://www.cnblogs.com/fengff/p/10367136.html
Copyright © 2011-2022 走看看