How can you remove the first and last characters from a string easily in Python? Can it be done using just one line of code?
To remove the first and last characters from a string in Python use the
slice operator
on the string to return the needed characters, for example,
my_string[1:-1]
.
Here is an example demonstrating the technique:
>>> my_string = "<html>"
>>> my_string[1:-1]
'html'
Slice Notation: How Does It Work?
The powerful slice operator in Python allows you to capture a range according to the following pattern:
[start:stop:step]
The first parameter
start
is the starting index number of the capture of the string and includes that index position. As the first index number starts at 0, the number 1 denotes the
second last character
, so be careful when defining your starting position.
Therefore, when removing the
first
character of the string, you will want the starting capture to begin at the index number
1
– which is why the slice operator
[1:-1]
for removing the first and last character, has the
start
parameter as the value
1
(not 2).
The second parameter in the slice operator is the
stop
parameter that defines the
end
of the capture and
excludes
that character. The negative index number
-1
in Python means the last element in the range.
Therefore, using the slicing technique
[1:-1]
the capture starts from the
second character
in the string and captures all other characters up to and
excluding
the last element in the string.
If you want to capture the new string as its own variable without modifying the original string, you will need to store the result in a new variable, like so:
>>> original_string = "<html>"
>>> new_string = original_string[1:-1]
>>> print(new_string)
'html'
>>> print(original_string)
'<html>'
Empty String Result
What happens if your original string is empty?
Here’s the result of performing the slice operation on an empty string:
>>> my_empty_string = ""
>>> my_empty_string[1:-1]
''
Notice that it produces an empty string itself!
If you don’t want this result, you might need to check if the original string is already empty, perhaps something like this:
if my_empty_string and type(my_empty_string) == str:
print(my_empty_string[1:-1]
else:
print("my_empty_string is empty")
Remove First Character From A String
If your use case is to just remove the first letter from your string using Python, you can still use the list operator to achieve you result in just one line of code.
Here is a demonstration first:
>>> my_string = "How long is a piece of string?"
>>> my_string[1:]
'ow long is a piece of string?'
Notice in the above example how the first character has been removed. By using the slice operator on the string the capture in the range is from the second element to the very end of a string as no number has been inserted after the colon.
Without having a second number in the slice operator Python assumes that the capture goes through to the end.
But what if you wanted to remove just the last character of the string can the slice operator be used to do this as well? Of course!
Remove Last Character Of String
In a similar way to how you remove the first character of each string using the slice operator you can use the same operator to remove just the last character.
As mentioned above the
second
number in the slice operator performs the capture up to and
excluding
that indexed item. Therefore, to capture everything from the beginning of the string to the end and excluding the end the slice operation needed would just be
my_string[:-1]
.
Here is an example demonstrating this operation:
>>> my_string = "How long is a piece of string?"
>>> my_string[:-1]
'How long is a piece of string'
As you can see the question mark at the very end of the string has been removed by using the slice operator . In this instance there is no number to denote the starting index position, if this is blank then it is assumed the capture starts from the first element or character in the case of a string.
The second number in the slice operator as previously explained captures everything up to and excluding that item. The index number -1 means the last item in the string, therefore, by using this as the second number in the slice operator everything is captured up to the last character, but excluding that last character.
What if you wanted to remove every other character except for the first and last characters in a string? Can this be done in Python using the slice operator too? Of course!
Remove Everything Except For First & Last Characters In String
If you needed to remove everything in a string except for the first and last characters in the string you can apply the slice operator but it involves one last aspect not yet revealed about the slice operator: the third parameter.
As seen above the slice operator has taken the form
x:y
where
x
is the starting index number, and
y
is the ending index number (exclusive). However, there’s also another form of the slice operator that involves a third parameter and takes the form
x:y:z
where
z
is the step from start to end with the default step value being 1.
Here is a quick example demonstrating the step parameter in the slice operator:
>>> my_string = "How long is a piece of string?"
>>> my_string[::2]
'Hwln sapeeo tig'
In the above example the slice operation captures each second character from start to end and the result is displayed in the REPL.
So how can you use this third parameter to only capture the first and last characters of a string?
In the same way, the step was used to capture every second character above the same principle can be used to capture just the first and last character, except the step would just need to be the size of the string less one character .
Here’s a quick example demonstrating how you can do this:
>>> my_string = "How long is a piece of string?"
>>> my_string[::len(my_string)-1]
'H?'
As you can see from the above example the first and last characters from the string have been captured using the versatile slice operator and only the step parameter. With no parameters set for the first and second section of the operator it means the capture has started at the beginning and has progressed through to the very end of the string with the step defining the jump from the start to the end.
To help define the length of the string the
len()
built-in function has helped and we need to subtract one from this amount otherwise the jump goes beyond the string because we are jumping from the first character.
Using Built-In Function
strip()
If you’re using this slicing technique to remove any leading or trailing whitespace, there is another easier way to do this with the built-in methods, namely,
strip()
.
For example,
>>> my_string = " <html> "
>>> my_string[1:-1]
'<html>'
>>> print(my_string)
' <html> '
>>> my_string.strip()
'<html>'
>>> print(my_string)
' <html> '
Both the slicing technique and the
.strip()
method on the string achieve the same result without modifying the original string.
Remove First And Last Characters From Python String
The slice operator is a handy syntax for being able to remove the first and last characters from a string in Python. The same operator can similarly be used to remove just the first character or just the last character as well.
In this article, you also explored how to capture just the first and last characters of a string using the slice operators’ step parameter.