English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operation

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python string splitlines() usage and example

Python string methods

The splitlines() method splits the string at the newline characters and returns a list of lines in the string.

The syntax of splitlines() is:

str.splitlines([keepends])

splitlines() parameter

splitlines() can contain at most1Parameter.

keepends (Optional)-If keepends is provided and is True, then the newline characters are also included in the items of the list.

By default, it does not contain newline characters.

splitlines() return value

splitlines() returns a list of lines in the string.

If there is no newline character, it returns a list containing a single item (a single line).

splitlines() splits at the following line boundaries:

MeansDescription
\nNew line
\rCarriage return
\r\nCarriage return+New line
\v Or \x0bLine tab
\f Or \x0cForm feed
\x1cFile separator
\x1dField separator
\x1eRecord separator
\x85Next line (C1Specify code)
\u2028Line separator
\u2029Paragraph separator

Example: How does splitlines() work?

grocery = 'Milk
Chicken
Bread
Butter'
print(grocery.splitlines())
print(grocery.splitlines(True))
grocery = 'Milk Chicken Bread Butter'
print(grocery.splitlines())

When running the program, the output is:

['Milk', 'Chicken', 'Bread', 'Butter']
['Milk', 'Chicken', 'Bread', 'Butter']
['Milk Chicken Bread Butter']

Python string methods