Python string splitlines() method
In this post, you will learn about the Python splitlines() method.
Python splitlines() method splits a string into a list at the specified line boundaries. The line breakers can be a new line (\n), carriage return (\r) , line tabulator (\v) etc. This function returns a list of lines in the string, including the optional line break.
Syntax of splitlines()
string.splitlines(keeplinebreaks)
This method accepts only one parameter 'keeplinebreaks', which is optional. If it is set to true, line breaks also need to be included in the output. The default value is false.
These are the possible 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 |
\u2028 | Line Separator |
\u2029 | Paragraph Separator |
Examples of Python splitlines() method
In the given code, variable x splits the string without keeping the line break, but the variable y splits the string with keeping the line breaks.
txt = "etutorialspoint provides \n good educational resources."
x = txt.splitlines()
y = txt.splitlines(True)
print(x)
print(y)
Output of the above code -
['etutorialspoint provides ', ' good educational resources.']
['etutorialspoint provides \n', ' good educational resources.']
As you can see in the above example, the string has been applied over splitlines() method without keeping any 'keeplinebreaks' argument in the x variable, the print() statement prints the list of strings without including the line break. We set this 'True' in the 'y' variable, and the statement prints the list of strings with the line break.
Other examples of splitlines() method
items = 'Garlic\nOnion\r\nPotato\rChilli'
print(items.splitlines())
print(items.splitlines(True))
items1 = 'Milk Sugar Salt Spices'
print(items1.splitlines())
print(items1.splitlines(True))
Output of the above code -
['Garlic', 'Onion', 'Potato', 'Chilli']
['Garlic\n', 'Onion\r\n', 'Potato\r', 'Chilli']
['Milk Sugar Salt Spices']
['Milk Sugar Salt Spices']
Related Articles
Greatest common divisor Python recursive
Python String isalpha() Method
Program to print ASCII Value of a character
Python program to sort words in alphabetical order
*args and **kwargs in Python
Printing Simple Diamond Pattern in Python
Stemming and Lemmatization in Python
Python | Generate QR Code using pyqrcode module
Text Detection and Extraction using OpenCV and OCR
Python Random shuffle() Method
Fibonacci Series In Python | Python Program To Print
File Handling in Python
Python - XML to JSON
Python XML to Dictionary
Serialize Python dictionary to XML