Remove the first N lines from a String in Python

avatar

Borislav Hadzhiev

Last updated: Aug 14, 2022

banner

Photo from Unsplash

Remove the first N lines from a String in Python #

To remove the first N lines from a string:

  1. Use the str.split() method to split the string on each newline character.
  2. Only split the string N times.
  3. Access the list item at index N.
  4. The new string won't contain the first N lines of the original string.
main.py
my_str = """\ first line second line third line fourth line""" # ✅ Remove first line from a string result = my_str.split('\n', 1)[1] # second line # third line # fourth line # print(result) # ---------------------------------- # ✅ Remove first two lines from a string result_2 = my_str.split('\n', 2)[2] # third line # fourth line print(result_2) # ---------------------------------- # ✅ Remove first three lines from a string result_3 = my_str.split('\n', 3)[3] # fourth line print(result_3)

We used the str.split() method to remove the first N lines from a string.

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)
main.py
my_str = """\ first line second line third line fourth line""" # 👇️ ['first line', 'second line\nthird line \nfourth line'] print(my_str.split('\n', 1))
We split the string on each \n character and only split it N times.

The example above splits the string once on a newline character.

The last step is to access the list item at index N to get the remainder of the string.

main.py
my_str = """\ first line second line third line fourth line""" # second line # third line # fourth line print(my_str.split('\n', 1)[1])

If you need to remove the first 2 lines from the string, you'd split it on each newline character 2 times and you'd access the list item at index 2.

main.py
my_str = """\ first line second line third line fourth line""" # third line # fourth line print(my_str.split('\n', 2)[2])
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.