3 easy ways to remove the last characters of a string in Python

Renesh Bedre    1 minute read

In this article, I will discuss how to remove the last number of characters from a string using Python.

As strings are iterable, you can use index and slice methods to access the individual or group of characters within the strings.

Using string slices

In slice, the first character of the string starts with 0 and the last character of the string starts with -1 (equivalent to len(string) - 1).

Remove the last character in a string using a negative index,

x = 'ATGCATTTC'
# # Remove last character
x[:-1]
'ATGCATTT'

# Remove last 2 characters
x[:-2]
'ATGCATT'

Remove the last character in a string using a positive index,

x[:len(x)-1]    # Note: -1 is equivalent len(x)-1
'ATGCATTT'

# Remove last 2 characters
x[:len(x)-2]
'ATGCATT'

Using string rstrip() function

If you know the last character of a string, you can use the rstrip() function

x.rstrip('C')
'ATGCATTT'

You can also remove special characters such as whitespace using rstrip() function

y = 'ATGCATTTC '
y.rstrip()
'ATGCATTTC'

Using list

Strings can be converted to a list to remove the last character in a string

''.join(list(x)[:-1])
'ATGCATTT'

Learn more about Python

If you have any questions, comments or recommendations, please email me at reneshbe@gmail.com

This work is licensed under a Creative Commons Attribution 4.0 International License