Python String - Remove first and last character
Python String - Remove first and last character
To remove first and last character from a string in Python, you can use string slicing. Slice the string with start index = 1, and stop index = -1.
In this tutorial, we shall go through examples where we shall take a sample string, and remove the first and last characters.
1. Remove first and last character from the string using slicing in Python
Consider that we are given a string in x, and we have to remove the first and last character from this string x.
Steps
- Given a string in x.
x = "Hello World"
- Use slice to discard the first and last character of string x.
x[1:-1]
- The string slice returns a new string with the first and last character removed from the original string. Store it in a variable, x_sliced.
x_sliced = x[1:-1]
- You may print the resulting string to output.
print(x_sliced)
Program
The complete program to remove the first and last characters from the string using slicing.
Python Program
# Take a string
x = "Hello World"
# Slice to remove first and last characters
x_sliced = x[1:-1]
print(f"Resulting string : \"{x_sliced}\"")
Output
Resulting string : "ello Worl"
You may need to check the string length before slicing the string, because, if the string length is less than or equal to two, then the string slice returns an empty string.
Let us see the result when the length of given string is less than or equal to two.
Program
The program to remove the first and last characters from the string using slicing, when the length of the string is two.
Python Program
# Take a string
x = "He"
# Slice to remove first and last characters
x_sliced = x[1:-1]
print(f"Resulting string : \"{x_sliced}\"")
Output
Resulting string : ""
The program to remove the first and last characters from the string using slicing, when the length of the string is one.
Python Program
# Take a string
x = "H"
# Slice to remove first and last characters
x_sliced = x[1:-1]
print(f"Resulting string : \"{x_sliced}\"")
Output
Resulting string : ""
The program to remove the first and last characters from an empty string using slicing.
Python Program
# Take a string
x = ""
# Slice to remove first and last characters
x_sliced = x[1:-1]
print(f"Resulting string : \"{x_sliced}\"")
Output
Resulting string : ""
You may use a Python if else statement to notify if the length of the string is less than two.
Python Program
# Take a string
x = "H"
if len(x) >= 2:
# Slice to remove first and last characters
x_sliced = x[1:-1]
print(f"Resulting string : \"{x_sliced}\"")
else:
print("Length of string is less than two.")
Output
Length of string is less than two.
Summary
In this tutorial, we learned how to remove first and last characters of a string using string slicing, with an example program explained with steps in detail.