zoukankan      html  css  js  c++  java
  • python里的splitlines具体解释

        Python的split方法函数能够切割字符串成列表,默认是以空格作为分隔符sep来切割字符串。

    In [1]: s = "www jeapedu com"
    
    In [2]: print s.split()
    ['www', 'jeapedu', 'com']
    

        当然能够改变sep切割字符串为其它字符串。

    In [6]: t = "www.jeapedu.com"
    
    In [7]: print t.split(".")
    ['www', 'jeapedu', 'com']
    


        python的字符串类里还提供了splitlines方法函数。

    splitlines(...)
        S.splitlines(keepends=False) -> list of strings
        
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
    
        splitlines函数什么意思呢?

    In [8]: u = "www.jeapedu.com
    www.chinagame.me
    www.quanzhan.org"
    
    In [9]: print u.splitlines()
    ['www.jeapedu.com', 'www.chinagame.me', 'www.quanzhan.org']
    
        这个样例不好。由于用split(' ')也能够切割成上面的结果。

    In [13]: u = "www.jeapedu.com
    www.chinagame.me
    www.quanzhan.org"
    
    In [14]: print u.split("
    ")
    ['www.jeapedu.com', 'www.chinagame.me', 'www.quanzhan.org']
    
        结果一样,可是以下的測试用例就必须用splitlines了。

    t =  """www.jeapedu.com
           www.chinagame.me
           www.quanzhan.org
         """
        print t.splitlines()
    

         程序结果例如以下所看到的:

    ['www.jeapedu.com', '       www.chinagame.me', '   www.quanzhan.org']
    

           结果不太好,用strip函数去掉字符串前后的空格。

       好,至此splitlines的基本使用已经解析完毕,那splitlines里的參数keepends又是什么意思呢?

    t =  """www.jeapedu.com
           www.chinagame.me
           www.quanzhan.org
         """
    print t.splitlines()
    print t.splitlines(True)
    
        默认splitelines參数keepends为False,意思是不保留每行结尾的 , 而keepends为True时。切割的每一行里尾部会有 。

        总结,splitlines是按行切割字符串,返回值也是个列表。




    -----------------------------------------------------------

  • 相关阅读:
    Python staticmethod
    pandas通过字典生成dataframe
    关于series的统计
    python的*args与**kwargs
    python global
    matplotlib画子图时设置总标题
    matplotlib两种画散点图的方式
    idea下web工程的编译和输出设置
    Vue&webpack入门实践
    《图解设计模式》读书笔记6-1 VISITOR模式
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10535272.html
Copyright © 2011-2022 走看看