The Python method splitlines is utilized to divide a string according to its line breaks. It segments the string at the points where lines end and produces a list of the resulting substrings. The line separators may include new line characters (\n), carriage returns (\r), among others. Below is a table detailing the various line break characters that can be used to split the string.
This method splits on the given line boundaries.
| Representation | Description |
|---|---|
n |
Line Feed |
r |
Carriage Return |
rn |
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 |
Signature
splitlines([keepends])
Parameters
keepends: This parameter is a boolean type that can take on the values of either True or False. It is not mandatory.
Return
It returns a comma separated list of lines.
Let us explore a few instances of the splitlines method to gain a clearer understanding of how it operates.
Python String splitlines Method Example 1
# Python splitlines() method example
# Variable declaration
str = "Python is a programming language"
# Calling function
str2 = str.splitlines() # returns a list having single element
print(str)
print(str2)
str = "Java \n is a programming \r language"
str2 = str.splitlines() # returns a list having splitted elements
print(str2)
Output:
Python is a programming language
['Python is a programming language']
['Python ', ' is a programming ', ' language']
Python String splitlines Method Example 2
By providing a value of True to the method, it results in the incorporation of line breaks within the string array. Refer to the example shown below.
# Python splitlines() method example
# Variable declaration
str = "Java \n is a programming \r language"
# Calling function
str2 = str.splitlines(True) # returns a list having splitted elements
print(str2)
Output:
['Java \n', ' is a programming \r', ' language']
Python String splitlines Method Example 3
# Python splitlines() method example
# Variable declaration
str = "Java \n is a programming \r language for \r\n software development"
# Calling function
str2 = str.splitlines() # returns a list having splitted elements
# Displaying result
print(str2)
# getting back list to string
print("".join(str2)) # now it does not contain any line breaker character
Output:
['Python ', ' is a programming ', ' language for ', ' software development']
Java is a programming language for software development