How to Remove the First and Last Character from a String in Python

Updated onbyAlan Morel
How to Remove the First and Last Character from a String in Python

String manipulation is one of the most common yet basic operations to do in Python.

Thankfully, Python makes it easy to work with strings and do things like remove characters from the beginning and end of a string.

In this post, we'll look at examples of how to remove the first and last characters from a string in Python.

Removing the First Character

First, let's start off with our example string:

PYTHON
str = "Hello World" print(str)
BASH
Hello World

Now let's use the slice notation to remove the first character from the string:

PYTHON
str = "Hello World" str = str[1:] print(str)
BASH
ello World

The str[1:] notation is used to remove the first character from the string because the first character is at index 0, so we can cut it out by starting at index 1.

We leave the second part of the notation blank so that it reads until the very end of the string.

Removing the Last Character

Similarly, we can use the str[:-1] notation to remove the last character from the string:

PYTHON
str = "Hello World" str = str[:-1] print(str)
BASH
Hello Worl

The same logic applies here as well.

We are using -1 to tell the compiler to start at the end of the string and go backwards by one character.

We leave the start of the notation blank so it starts from the beginning of the string.

Together, this has the effect of removing the last character from the string.

Conclusion

In this post, we learned how to use the slice notation to remove the first and last characters from a string.

Simply passing the str[1:] notation to the slice function will remove the first character from the string, and similarly, passing str[:-1] will remove the last character from the string.

Hopefully, this post has been useful to you.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.