Python String | splitlines()
Python String splitlines() Method
The Python string splitlines() method is used to split lines at line boundaries. This function returns a list of the number of lines in the string, including (optional) newlines.
Syntax:
string.splitlines([keepends])
Parameters:
keepends (Optional) : When set to True, newlines will be included in the resulting list. This can be a number specifying line breaks, or any Unicode character such as “n”, “r”, “rn”, etc., used as a string boundary.
Return Value:
Returns a list of the lines in string, broken at line boundaries.
splitlines() splits on the following line boundaries:
Representation | Description |
---|---|
n | Newline |
r | Carriage Return |
rn | Carriage Return + Line Feed |
x1c | File Separator |
x1d | Group Separator |
x1e | Record Separator |
x85 | Next Line (C1 Control Code) |
v or x0b | Row-style table |
f or x0c | Table |
u2028 | Row separator |
u2029 | Paragraph separator |
Example 1
# Python code to illustrate splitlines()
string = "Welcome everyone torthe world of GeeksnGeeksforGeeks"
# No parameters has been passed
print (string.splitlines( ))
# A specified number is passed
print (string.splitlines(0))
# True has been passed
print(string.splitlines(True))
Output:
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone tor', 'the world of Geeksn', 'GeeksforGeeks']
Example 2
# Python code to illustrate splitlines()
string = "CatnBatnSatnMatnXatnEat"
# No parameters has been passed
print (string.splitlines( ))
# splitlines() in one line
print('IndianJapannUSAnUKnCanadan'.splitlines())
Output:
['Cat', 'Bat', 'Sat', 'Mat', 'Xat', 'Eat']
['India', 'Japan', 'USA', 'UK', 'Canada']
Example 3: Practical Application
In this code, we will see how to use the splitlines() concept to calculate the length of each word in a string.
# Python code to get the length of each word
def Cal_len(string):
# Using splitlines() to divide into a list
li = string.splitlines()
print (li)
# Calculate length of each word
l = [len(element) for element in li]
Return l
#DriverCode
string = "WelcomertorGeeksforGeeks"
print(Cal_len(string))
Output:
['Welcome', 'to', 'GeeksforGeeks']
[7, 2, 13]