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 Dictionary keys()
Generate a String
Python print()
Python Inheritance
Python Program to Iterate Through Two Lists in Parallel
Python String maketrans()
Reading an HTTP Response Body as a String in Java
Python timestamp to datetime and vice-versa
Format ZonedDateTime to String
Python Dictionary copy()
Python Program to Print Output Without a Newline
Python classmethod()
Python vars()
Map to String Conversion in Java
Python ord()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Convert Kilometers to Miles
Python Program to Convert Bytes to a String
Python max()
Python String zfill()
Python String index()
Python String replace()
Python Set symmetric_difference()
Python Program to Print Colored Text to the Terminal
Python enumerate()
Python Type Conversion and Type Casting
Python filter()
Python Program to Print the Fibonacci sequence
Jackson – Marshall String to JsonNode
Python String count()
Python String islower()
Python Program to Append to a File