Python String – Remove last N characters

Python String – Remove last N characters

To remove the last N characters from a string in Python, you can use string slicing. Slice the string with stop index = -N. Please note that we have using negative indexing in the slice expression to remove the last N character.

In this tutorial, we shall go through examples where we shall take a sample string, and remove the last N characters from the string.

1. Remove last N characters from the string using slicing in Python

Consider that we are given a string in x, and we have to remove the last N characters from this string x.

Steps

  1. Given a string in x.
x = "Hello World"
  1. Use slice to discard the last N characters of string x. And the slice expression is
x[:-N]
  1. The string slice returns a new string with the last N characters discarded from the original string. Store it in a variable, x_sliced.
x_sliced = x[:-N]
  1. You may print the resulting string to output.
print(x_sliced)

Program

The complete program to remove the last N characters from the string using slicing.

Python Program

# Take a string
x = "Hello World"

# Given N
N = 4

# Slice to remove last N characters
x_sliced = x[:-N]

print(f"Resulting string : \"{x_sliced}\"")
Run Code Copy

Output

Resulting string : "Hello W"

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 last N characters
    x_sliced = x[:-N]
    print(f"Resulting string : \"{x_sliced}\"")
else:
    print(f"Length of string is less than {N}.")
Run Code Copy

Output

Length of string is less than 4.

Summary

In this tutorial, we learned how to remove last N characters from a string using string slicing, with an example program explained with steps in detail.

Code copied to clipboard successfully 👍