Python String splitlines() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

Python String splitlines() method

The splitlines() method in Python splits the string at line breaks and returns a list of lines in the string.

The following symbols are considered as line breaks for splitlines().

  1. \n - Line Feed
  2. \r - Carriage Return
  3. \r\n - Carriage Return and Line Feed
  4. \v - Line Tabulation
  5. \f- Form Feed
Syntax of splitlines() method
string.splitlines(keepends)

keepends: Specifies if the line breaks 
          should be included - True or False(Optional)
          Default value is False. 
Example

Code/Output

str1 = "Pylenin loves Python.\nHe also likes Apples."
print(str1.splitlines())
>>> ['Pylenin loves Python.', 'He also likes Apples.']

str1 = "Pylenin loves Python.\nHe also likes Apples."
print(str1.splitlines(True))
>>> ['Pylenin loves Python.\n', 'He also likes Apples.']

str1 = "Pylenin\rPython\nApples\r\nBlogs\vYoutube\f"
print(str1.splitlines())
>>> ['Pylenin', 'Python', 'Apples', 'Blogs', 'Youtube']

str1 = "Pylenin\rPython\nApples\r\nBlogs\vYoutube\f"
print(str1.splitlines(True))
>>> ['Pylenin\r', 'Python\n', 'Apples\r\n', 'Blogs\x0b', 'Youtube\x0c']

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide