Skip to content
Related Articles

Related Articles

Python String splitlines() Method

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 19 Aug, 2021
Improve Article
Save Article

Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional).




keepends (optional): When set to True line breaks are included in the resulting list. This can be a number, specifying the position of line break or, can be any Unicode characters, like “\n”, “\r”, “\r\n”, etc as boundaries for strings.

Return Value: 

Returns a list of the lines in the string, breaking at line boundaries.

splitlines() splits on the following line boundaries:



\nLine Feed
\rCarriage Return
\r\nCarriage Return + Line Feed
\x1cFile Separator
\x1dGroup Separator
\x1eRecord Separator
\x85Next Line (C1 Control Code)
\v or \x0bLine Tabulation
\f or \x0cForm Feed
\u2028Line Separator
\u2029Paragraph Separator

Example 1


# Python code to illustrate splitlines()
string = "Welcome everyone to\rthe world of Geeks\nGeeksforGeeks"
# 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))


['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to\r', 'the world of Geeks\n', 'GeeksforGeeks']

Example 2


# Python code to illustrate splitlines()
string = "Cat\nBat\nSat\nMat\nXat\nEat"
# No parameters has been passed
print (string.splitlines( ))
# splitlines() in one line


['Cat', 'Bat', 'Sat', 'Mat', 'Xat', 'Eat']
['India', 'Japan', 'USA', 'UK', 'Canada']

Example 3: Practical Application

In this code, we will understand how to use the concept of splitlines() to calculate the length of each word in a string. 


# Python code to get length of each words
def Cal_len(string):
    # Using splitlines() divide into a list
    li = string.splitlines()
    print (li)
    # Calculate length of each word
    l = [len(element) for element in li]
    return l
# Driver Code    
string = "Welcome\rto\rGeeksforGeeks"


['Welcome', 'to', 'GeeksforGeeks']
[7, 2, 13]

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!