How to Remove the First and Last Character from a String in Python
Table of Contents
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:
PYTHONstr = "Hello World"
print(str)
BASHHello World
Now let's use the slice notation to remove the first character from the string:
PYTHONstr = "Hello World"
str = str[1:]
print(str)
BASHello 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:
PYTHONstr = "Hello World"
str = str[:-1]
print(str)
BASHHello 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!
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js