Python splitlines() Method

Python 字符串Python String


Description

Python splitlines() splits by line ('\r', '\r\n', \n'), returning a list containing each line as an element. If the parameter keepends is False, line breaks are not included; if True, line breaks are preserved.

Syntax

Syntax of the splitlines() method:

str.splitlines([keepends])

Parameters

  • keepends -- Whether to preserve line breaks ('\r', '\r\n', \n') in the output. The default is False, meaning line breaks are not included; if True, line breaks are preserved.

Return Value

Returns a list containing each line as an element.

Example

The following example demonstrates how to use the splitlines() function:

Example (Python 2.0+)

#!/usr/bin/python str1 = 'ab c\n\nde fg\rkl\r\n' print str1.splitlines(); str2 = 'ab c\n\nde fg\rkl\r\n' print str2.splitlines(True)

The output of the above example is:

['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

Python 字符串Python String

Other Extensions