Python中splitlines()方法的使用简介

yipeiwu_com5年前Python基础

 splitlines()方法返回一个字符串的所有行,可选包括换行符列表(如果num提供,则为true)
语法

以下是splitlines()方法的语法:

str.splitlines( num=string.count('\n'))

参数

  •     num -- 这是任何数,如果存在它会被认为换行需要被包括行数。

返回值

如果找到匹配的字符串此方法返回true,否则为false。
例子

下面的例子显示splitlines()方法的使用。

#!/usr/bin/python

str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print str.splitlines( );
print str.splitlines( 0 );
print str.splitlines( 3 );
print str.splitlines( 4 );
print str.splitlines( 5 );

当我们运行上面的程序,它会产生以下结果:

['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']

相关文章

深入源码解析Python中的对象与类型

深入源码解析Python中的对象与类型

对象 对象, 在C语言是如何实现的? Python中对象分为两类: 定长(int等), 非定长(list/dict等) 所有对象都有一些相同的东西, 源码中定义为PyObject...

Python的多态性实例分析

本文实例讲述了Python的多态性。分享给大家供大家参考。具体如下: #!/usr/bin/env python # polymorphism in python # class b...

python控制台显示时钟的示例

复制代码 代码如下:#!/usr/bin/env python# coding: utf-8### show time in console#import sysimport time...

创建pycharm的自定义python模板方法

在pycharm上依次选择打开File->settings->Editor->File andCode Templates->Python Script 复制以下...

简述Python2与Python3的不同点

在Python2和Python3中都提供print()方法来打印信息,但两个版本间的print稍微有差异 主要体现在以下几个方面: 1.python3中print是一个内置函数,有多个参...