AppDividend
Latest Code Tutorials

How to Remove Last Character From String in Python

0

Strings in Python can be indexed, with the first character having index 0. A character is simply a string of size one. Indices can also be negative numbers to start counting from the right. The -0 is the same as 0, and negative indices start from -1. So Python supports negative index slicing along with positive slicing.

To get the substring, you can use the slicing as follows.

data = "Apple will come up with new iPhone 13"

print(data[18:21])

Output

 wi

The string index starts with 0. So it will return the position of 18, 19, and 20, which is whitespace, w, and i. That’s the substring we get when we use the string slicing. One thing to note that it will not count the last character of the slice; it will only give up to the last character and not including the last character.

Let’s see how to remove the final character from the string.

Python Remove Last Character From String

To remove the last character from the string in Python, use string slicing. The string slicing allows you to obtain a substring. The indexing is used to get individual characters from the string.

Code snippet

str[:-1]

Here, the str can be any string whose last character you want to remove.

data = "Dogecoin"

print(data[:-1])

Output

Dogecoi

You can see that we successfully removed the last character of the Dogecoin string.

To get the last character of the string, you can write the following code.

data = "Dogecoin"

print(data[-1])

Output

n

And you will get the last character of the string. We used negative indexing to get the last character of the string in Python.

How to remove the first character of the string

To remove the first character of the string in Python, use string slicing. String slicing is the way of getting substring from a string, and it is also a way to get rid of any characters from the string.

data = "Dogecoin"

print(data[1:])

Output

ogecoin

You can see that the first character, “D” is removed from the string.

To get the first character of the string, use just negative indexing.

data = "Dogecoin"

print(data[-len(data)])

Output

D

This is how you can get the first character of the string in Python. The len() function returns the length of the string.

Using rstrip() to remove the last character

The rstrip() is a built-in Python function that returns a String copy with trailing characters removed. We can use the rstrip() function with negative indexing to remove the final character of the string.

data = "Dogecoin"

data = data.rstrip(data[-1])

print(data)

Output

Dogecoi

In this example, we have provided the last character of the string to the strip() method. It removes the last character from the string and returns a copy without the last character.

That is it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.