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

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

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:

RepresentsDescription
\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\nChicken\r\nBread\rButter'
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