Python String - Remove First Line


Python String - Remove first line

To remove the first line from a multiline string in Python, you can find the index of the first new line character in the string, and then find the substring of the string from that index to the end of the string.

In this tutorial, we shall go through examples where we shall take a sample string, and remove the first line from the string.

1. Remove first line from the string using string find() method and string slicing in Python

Consider that we are given a multiline string in x, and we have to remove the first line from this string x.

Steps

  1. Given a multiline string in x.
x = "This is line 1.\nThis is line 2.\nThis is line 3."
  1. Call find() method on the string x, and pass new line character as argument. The find() method returns the first occurrence of the new line character in the string. Store the returned index in a variable, say new_line_index.
new_line_index = x.find('\n')
  1. Take an empty string in a variable x_without_first_line. This variable is used to store the resulting string after removing the first line from given x.
  2. If an occurrence of new line character is found in the string, then find the substring after this index of new line till the end of the string. Store it in the variable, x_without_first_line.
x_without_first_line = x[new_line_index+1:]

Please note that we have added one to the new_line_index to discard the first new line character as well in the string slice.

  1. You may print the resulting string to output.
print(x_without_first_line)

Program

The complete program to remove the first line from the given string using string find() method, and string slicing.

Python Program

# Take a string
x = "This is line 1.\nThis is line 2.\nThis is line 3."

# Given N
new_line_index = x.find('\n')

# Variable to hold resulting string
x_without_first_line = ''

if new_line_index > -1:
    # Remove first line
    x_without_first_line = x[new_line_index+1:]

print(f"Given string\n\"{x}\"\n")
print(f"Result string\n\"{x_without_first_line}\"")

Output

Given string
"This is line 1.
This is line 2.
This is line 3."

Result string
"This is line 2.
This is line 3."

You may write the code as a function if you use this functionality more often.

Python Program

def remove_first_line(x):
    # Given N
    new_line_index = x.find('\n')

    # Variable to hold resulting string
    x_without_first_line = ''

    if new_line_index > -1:
        # Remove first line
        x_without_first_line = x[new_line_index+1:]

    return x_without_first_line

# Take a string
x = "This is line 1.\nThis is line 2.\nThis is line 3."

print(f"Given string\n\"{x}\"\n")
print(f"Result string\n\"{remove_first_line(x)}\"")

Summary

In this tutorial, we learned how to remove first line from a string using string find() method, and string slicing, with an example program explained with steps in detail.