Online Tutorials & Training Materials | STechies.com
Register Login

Python Remove last Character from String

12 Aug 2019 1:01 pm || 0

String manipulation is one of the most important aspects of Python. You can manipulate strings using slicing techniques, looping over the elements and string methods. Methods such as count(), find(), format(), upper(), index() and split() can be used. But there may be a situation, where you want to remove the initial or last character from a string. 

Remove First and Last Character from String

In this tutorial, you will learn how to remove the first and last character from string using an index.

In Python, each character of the string has its index. There are two types of indexes in python:

  • Left to right or Positive Index
  • Right to left or Negative Index

string

s

t

e

c

h

i

e

s

index

0

1

2

3

4

5

6

7

index

-8

-7

-6

-5

-4

-3

-2

-1

By using the string index, we can remove specific characters from the string.

Remove Last Character from String Python

Example:

# Python3 code to remove last character from string
# initializing test string
string='stechies'

# Remove last character
remove_last = string[:-1]

# Print remaining string
print(remove_last)

Output:

stechie

Explanation

Let us take a closer look at this code. You know that the indices in Python lists start from 0. The index -1 represents the last index of a list. Here, to remove the last character from the string, the string[:-1] is mentioned. This is because while printing the string, all the characters except the last one will be printed using the [:-1] technique. 

Python Remove First Character from String

Example:

# Python3 code to remove first character from string
# initializing test string
string='stechies'

# Remove first character
remove_first = string[1:]

# Print remaining string
print(remove_first)

Output:

techies

Explanation

In this code, the string[1:] is used to print the characters starting from index 1 till the end, without explicitly specifying the index of last element. This is useful as no matter what the length of the list is, you do not have to determine the last element’s index while slicing. Thus, this is an easy way to remove the initial character of any string as the index starts from 0, and it is ignored in this case using [:1].    

Conclusion

While mentioning the indices for removing characters from strings, remember that they start from 0. So, if you mention a[1:5], the second index will be considered but not the 6th index. The characters between the two indices will be printed to the screen. Moreover, if you mention a[1:], the elements from the second index till the last will be printed out. Negative indices should also be used carefully. This is to ensure that the final output is accurate.