splitlines() method of str class

The splitlines() tokenises a string with line separators into multiple tokens and returns the tokens as a list

Str Updated 14 Mar 2017 1 min read

Method Name

splitlines

Method Signature

splitlines()

Method Overview

  • splitlines() of Python str class, breaks a string into multiple strings based on a set of line separators and returns the result in a python list object.

  • The line separator characters include

Line SeparatorDescription
\nLine Feed
\rCarriage Return
\r\nCarriage Return and Line Feed
\v or \x0bLine Tabulation, Vertical Tab
\f or \x0cForm Feed
\x1cFile Separator
\x1dGroup Separator
\x1eRecord Separator
\x85Next Line
\u2028Line Separator
\u2029Paragraph Separator
  • Together with split() and splitlines()can be used to tokenize entire files of data which can be fed into relational data store or any other NoSQL data stores.

Example

python
sampleText = """The Little Prince is

a classic tale of equal appeal

to children and grown ups."""

lines           = sampleText.splitlines()

print(lines)

linesWithEnds   = sampleText.splitlines(keepends=True)

print(linesWithEnds)

Output

Output
['The Little Prince is', 'a classic tale of equal appeal ', 'to children and grown ups.']

['The Little Prince is\n', 'a classic tale of equal appeal \n', 'to children and grown ups.']