Table of Contents
The splitlines() method splits the string at line breaks and returns a list of lines in the string.
The syntax of splitlines() is:
str.splitlines([keepends])
1. splitlines() Parameters
splitlines() takes maximum of 1 parameter.
keepends (optional) – If keepends is provided and True, line breaks are also included in items of the list.
By default, the line breaks are not included.
2. Return Value from splitlines()
splitlines() returns a list of lines in the string.
If there are not line break characters, it returns a list with a single item (a single line).
splitlines() splits on the following line boundaries:
| Representation | Description |
|---|---|
| \n | Line Feed |
| \r | Carriage Return |
| \r\n | Carriage Return + Line Feed |
| \v or \x0b | Line Tabulation |
| \f or \x0c | Form Feed |
| \x1c | File Separator |
| \x1d | Group Separator |
| \x1e | Record Separator |
| \x85 | Next Line (C1 Control Code) |
| \u2028 | Line Separator |
| \u2029 | Paragraph Separator |
3. Example: How splitlines() works?
grocery = 'Milk\nChicken\r\nBread\rButter' print(grocery.splitlines()) print(grocery.splitlines(True)) grocery = 'Milk Chicken Bread Butter' print(grocery.splitlines())
Output
['Milk', 'Chicken', 'Bread', 'Butter'] ['Milk\n', 'Chicken\r\n', 'Bread\r', 'Butter'] ['Milk Chicken Bread Butter']
Related posts:
Python String capitalize()
Python Program to Display Calendar
Python Program to Print Output Without a Newline
Python Directory and Files Management
Array to String Conversions
How to get current date and time in Python?
Python Program to Parse a String to a Float or Int
Encode a String to UTF-8 in Java
Python Program to Check If a String Is a Number (Float)
Python Program to Measure the Elapsed Time in Python
Python Program to Get a Substring of a String
Python strptime()
Python Namespace and Scope
Python List
Python *args and **kwargs
Python Program to Access Index of a List Using for Loop
Python Program to Find the Sum of Natural Numbers
Python Program to Print all Prime Numbers in an Interval
Python List extend()
Java Program to Permute All Letters of an Input String
Python exec()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python open()
Python String isupper()
Python vars()
Python Program to Get the Class Name of an Instance
Python Set issubset()
Python compile()
Python all()
Check If a String Is Numeric in Java
Java InputStream to String
Python Generators