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

In this code, the variable string is initialized with the string value “stechies”. The string slicing technique is used in the next line. The string[ : -1] specifies all the characters of the string except the last one. The negative index -1 specifies the last character in the string “s”. The [:-1] specifies the character at index 0 and goes up to the index before the last one.

The last statement of the code prints out the value of the remove_last variable. The final output is:

stechie

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

Here, the variable string is assigned the value ‘stechies’. The remove_first variable is assigned the sliced value of the string. The code string[1:] specifies all the characters of the string starting from index 1 and till the last index. Thus, as the index starts from 0, the first character of the string is removed. The remaining characters of the string are printed to the screen in the next line of code.

Therefore, the final output is 

techies    

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.