Python str.splitlines() function


In Python, the str.splitlines() method is used to split a string into a list of lines. This method is particularly useful for processing multiline strings, as it separates the string at line breaks and returns a list containing each line as a separate element.

Syntax

str.splitlines(keepends=False)
  • keepends (optional): A boolean value that determines whether to include the line break characters (\n, \r, or \r\n) at the end of each line in the resulting list.
    • If True, the line breaks are included in the resulting list.
    • If False (the default), the line breaks are not included.

Example Usage

  1. Basic usage:
text = "Hello\nWorld\nPython" result = text.splitlines() print(result) # Output: ['Hello', 'World', 'Python']
  1. Including line breaks:

If you want to keep the line breaks in the resulting list, you can set keepends to True:

text = "Hello\nWorld\nPython" result = text.splitlines(keepends=True) print(result) # Output: ['Hello\n', 'World\n', 'Python']
  1. Different line break characters:

The splitlines() method can handle different types of line breaks, including carriage returns (\r) and a combination of both (\r\n):

text = "Line1\rLine2\r\nLine3" result = text.splitlines() print(result) # Output: ['Line1', 'Line2', 'Line3']
  1. Empty string:

If the string is empty, the result will be an empty list:

text = "" result = text.splitlines() print(result) # Output: []
  1. Trailing newlines:

If the string ends with a newline character, splitlines() will handle it gracefully. By default, the trailing newline is not included:

text = "Line1\nLine2\n" result = text.splitlines() print(result) # Output: ['Line1', 'Line2']

Summary

  • Use str.splitlines() to split a string into a list of lines based on line break characters.
  • The keepends parameter allows you to control whether the line breaks are included in the resulting list.
  • This method is useful for processing multiline strings, such as reading from text files or handling user input with multiple lines.