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!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Create an RSS Reader in Node
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript