Python program to remove the last character of a string:
This post will show you how to remove or delete the last character from a string in python. We can use different ways to remove the last character of a string. Since string is immutable, it will create one new string with the last character removed from it.
Method 1: By using negative index slicing:
We can use slicing to create one new string by using start and end indices. Let’s take a look at the below example:
given_str = 'Hello World'
print(given_str[0:10])
Here, the print method will print one string from index 0 to index 10.
The first index is optional. It considers the start index, i.e. 0. So, the below program will give the same result:
given_str = 'Hello World'
print(given_str[:10])
Negative index slicing:
Now, instead of providing a number i.e. length - 1 as the second index, we can also use negative index slicing, i.e. if we provide -1, it will take upto length - 1, if we provide -2, it will be length - 2 etc.
So, to remove the last character from a string, we can provide -1 as the second argument.
given_str = 'Hello World'
print(given_str[:-1])
It will print:
Hello Worl
i.e. the last character is removed.
We can also create one new variable to store the new string.
given_str = 'Hello World'
new_str = given_str[:-1]
print(new_str)
Method 2: By using rstrip:
rstrip method is used to remove the last character from the end of a string. It takes the character as the parameter. We can use negative indexing to get the last character of a string. Just pass that character to rstrip and it will return one new string by removing the last character.
given_str = 'Hello World'
new_str = given_str.rstrip(given_str[-1])
print(new_str)
We are passing the last character to given_str.rstrip. The newly created string is stored in new_str. It will print:
Hello Worl
You might also like:
- Python program to find the volume of a tetrahedron
- Python program to search for a text in a file
- How to insert an item to the start of an Ordered dictionary in Python
- How to write a simple stopwatch in python
- Python program to check if two sets are equal
- How to create a color choosing dialog in tkinter python