Python String splitlines()

Filed Under: Python
Python String splitlines()

Python String splitlines()

Python String splitlines() function returns the list of lines in the string. The line boundaries are not included in the string, unless we provide keepends argument value as True.

Python String splitlines()

The following table shows the characters that are treated as line boundary by splitlines() function.

Character Description
\n Line Feed
\r Carriage Return
\r\n Carriage Return + Line Feed
\v or \x0b Line Tabulation (Python 3.2 onwards)
\f or \x0c Form Feed (Python 3.2 onwards)
\x1c File Separator
\x1d Group Separator
\x1e Record Separator
\x85 Next Line (C1 Control Code)
\u2028 Line Separator
\u2029 Paragraph Separator

Python String split into lines

Let’s look into some examples of splitlines() function.


s = 'Java\nPython\nAndroid'

lines = s.splitlines()
print(lines)

lines = s.splitlines(keepends=True)
print(lines)

Output:


['Java', 'Python', 'Android']
['Java\n', 'Python\n', 'Android']

Let’s look at another example with a combination of line feed and carriage return characters.


s = 'Java\n\n\n\nPython\n\r\nAndroid'  # \r\n is treated as a single line boundary
lines = s.splitlines()
print(lines)

lines = s.splitlines(keepends=True)
print(lines)

Output:


['Java', '', '', '', 'Python', '', 'Android']
['Java\n', '\n', '\n', '\n', 'Python\n', '\r\n', 'Android']

If you get confused with the output from splitlines() function, test it with keepends as True to understand how the split is performed.

Finally, let’s look into some examples with different separator characters.


s = 'A\tB\vC\fD'
lines = s.splitlines()
print(lines)

lines = s.splitlines(keepends=True)
print(lines)

s = 'A\x1cB\x1dC\x1eD\x85E\u2028F\u2029G'
lines = s.splitlines()
print(lines)

lines = s.splitlines(keepends=True)
print(lines)

Output:


['A\tB', 'C', 'D']
['A\tB\x0b', 'C\x0c', 'D']
['A', 'B', 'C', 'D', 'E', 'F', 'G']
['A\x1c', 'B\x1d', 'C\x1e', 'D\x85', 'E\u2028', 'F\u2029', 'G']

Python String split() vs splitlines()

  • We can specify separator in split() function, splitlines() is only meant to split string into list of lines.
  • There are slight difference in the split() and splitlines() function working. Let’s see that with examples:
    
    print("".split('\n'))
    print("".splitlines())
    
    print("Hi\n".split('\n'))
    print("Hi\n".splitlines())
    

    Output:

    
    ['']
    []
    ['Hi', '']
    ['Hi']
    

    So with line break as separator, split() returns empty string in the list whereas splitlines() returns empty list.

You can checkout more Python examples from our GitHub Repository.

Official Documentation: partition()

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages