To remove the first and last character from a string in Python, the easiest way is to use slicing.

string = "This is a string variable"

string_without_first_last_char = string[1:-1]

print(string_without_first_last_char)

#Output:
his is a string variabl

When using string variables in Python, we can easily perform string manipulation to change the value of the string variables.

One such manipulation is to remove characters from a string variable.

With slicing, we can easily get rid of the first and last character from a string. To do so, we need to select all of the elements between the first and last character.

To keep everything between the first and last character, we should pass ‘1’ as the start position and ‘-1’ as the end position to create our slice.

Below is how we can truncate a string and remove the first and last character from a string in Python.

string = "This is a string variable"

string_without_first_last_char = string[1:-1]

print(string_without_first_last_char)

#Output:
his is a string variabl

How to Remove the First Character from a String in Python

If you just want to remove the first character from a string in Python, we can adjust our example from above.

To remove the first character in a string using slicing, we know that the first character has index ‘0’. So, to get everything except the first character, we start our slice at position ‘1’ and don’t provide an end position to get everything else in the string.

Below is an example of how to get rid of the first character in a string using Python.

string = "This is a string variable"

string_without_first_char = string[1:]

print(string_without_first_char)

#Output:
his is a string variable

How to Remove the Last Character from a String in Python

If you just want to remove the last character from a string in Python, we can adjust our example from above.

You can use slicing to remove the last character from a string in Python in a very similar way. To remove the last character in a string, pass ‘-1’ as the end position.

string = "This is a string variable"

string_without_last_char = string[:-1]

print(string_without_last_char)

#Output:
This is a string variabl

Hopefully this article has been useful for you to learn how to remove the first and last characters from a string in Python.

Categorized in:

Python,

Last Update: March 15, 2024