Python String - Remove first N characters
Python String - Remove first N characters
To remove the first N characters from a string in Python, you can use string slicing. Slice the string with start index = N.
In this tutorial, we shall go through examples where we shall take a sample string, and remove the first N characters from the string.
1. Remove first N characters from the string using slicing in Python
Consider that we are given a string in x, and we have to remove the first N characters from this string x.
Steps
- Given a string in x.
x = "Hello World"
- Use slice to discard the first N characters of string x.
x[N:]
- The string slice returns a new string with the first N characters discarded from the original string. Store it in a variable, x_sliced.
x_sliced = x[N:]
- You may print the resulting string to output.
print(x_sliced)
Program
The complete program to remove the first N characters from the string using slicing.
Python Program
# Take a string
x = "Hello World"
# Given N
N = 4
# Slice to remove first N characters
x_sliced = x[N:]
print(f"Resulting string : \"{x_sliced}\"")
Output
Resulting string : "o World"
Please not that you may need to check the string length before slicing the string, because, if the string length is less than N, then the string slice returns an empty string.
If you want to be notified when the length of the string is less than N, then you may use a Python if else statement as shown in the following program.
Python Program
# Take a string
x = "Hel"
# Given N
N = 4
if len(x) >= N:
# Slice to remove first N characters
x_sliced = x[N:]
print(f"Resulting string : \"{x_sliced}\"")
else:
print(f"Length of string is less than {N}.")
Output
Length of string is less than 4.
Summary
In this tutorial, we learned how to remove first N characters from a string using string slicing, with an example program explained with steps in detail.