remove last character from string in python

Remove Last Character from String in Python [7 Best Ways]

It’s typical to find yourself in a requirement to remove the last character from a string in Python. The reasons could be any one of the following.

  • Have read a file into a list of strings, where each line is having an extra new line or any other special character at the end.
  • Scrapped a web page for external links and all links with an unnecessary white space character at the last position

In this article, we will be discussing different ways in Python to remove the last character from a String with code snippets. But prior to that, we need to master the two crucial concepts used in these ways – Indexing and Slicing.

Quick Summary

We recommend using the below method to remove the last one or n characters from the string.

  • Using the slicing operator — code looks much clean and compact. less readable.
  • Using the slicing class — code will be readable
Don’t use rstrip()

Don’t recommend rstrip() method as it removes matching characters continuously not just the last characters.

Different ways to Remove Last Character From String

1. slicing operator

The string object is indexable and sliceable like a list, So we can use the slicing operator to remove the last character from the string.

A. Remove the last character from the String

To remove only the last character from String in Python, we can make use of a slicing operation with negative indexing.

Notes:

  • Slicing creates a new string and does not change the source string.

Code Thread:

# function to remove the last character using slicing operator
def remove_last_character(string):
    return string[:-1]


# director name with unintended characters like '.'
actual_director_name = 'James Cameron.'

corrected_director_name = remove_last_character(actual_director_name)

print(corrected_director_name)

Output:

James Cameron

B. remove last n characters from String

Last n characters removal from string in Python is simlar to above method. This method also create a new string without last n characters from source string and return it.

Code Thread:

# function to remove the last n characters using slicing operator
def remove_last_n_characters(string, n):
    return string[:-n]


# director name with unintended characters like '.$'
actual_director_name = 'James Cameron.$'

corrected_director_name = remove_last_n_characters(actual_director_name,2)

print(corrected_director_name)

Output:

James Cameron

2. slicing class

Alternatively, we can use slice class to remove the last character in Python. With slice name, this method is slightly more readable than the slicing operator method.

A. Remove last character from the String

Code Thread:

# function to remove the last character using slice class
def remove_last_character(string):
    part = slice(0, -1)
    return string[part]


# director name with unintended characters like '.'
actual_director_name = 'James Cameron.'

corrected_director_name = remove_last_character(actual_director_name)

print(corrected_director_name)

Output:

James Cameron

B. Remove last n characters from String

Here also we have used slice class with a negative index number to create a slice object and we sliced the string with created slice to remove the last n characters.

Code Thread:

# function to remove the last n characters using slicing class
def remove_last_n_characters(string, n):
    part = slice(0, -n)
    return string[part]


# director name with unintended characters like '.$'
actual_director_name = 'James Cameron.$'

corrected_director_name = remove_last_n_characters(actual_director_name, 2)

print(corrected_director_name)

Output:

James Cameron

3. len() function

This method also uses slice object, but it is created by using positive indexing. We create slice object that starts at 0 and ends at len(string) - 1 and created a new string with slicing without last character.

A. Remove last character from String

Code Thread:

# function to remove the last character using len() function
def remove_last_character(string):
    part = slice(0, len(string) - 1)
    return string[part]


# director name with unintended characters like '%'
actual_director_name = 'Steven Spielberg%'

corrected_director_name = remove_last_character(actual_director_name)

print(corrected_director_name)

Output:

Steven Spielberg

B. Remove last n characters from String

As we did in the method A, We create a slice object starting at 0 and ending at len(string)-n and slice the string to remove last n characters.

Code Thread:

# function which takes string as input and removes the last n characters using len() function and slice class
def remove_last_n_characters(string, n):
    part = slice(0, len(string) - n)
    return string[part]


# director name with unintended characters like '%_'
actual_director_name = 'Steven SpielBerg%_'

corrected_director_name = remove_last_n_characters(actual_director_name,2)

print(corrected_director_name)

Output:

Steven SpielBerg

4. rstrip() method

Python’s string class has a method named rstrip() to trim the string from the right side. By default, if no characters are given, it trims all the white space characters on the right side.

If given characters, it repeatedly removes the given the characters from right end until the source string does not contain the given characters at the end.

For Example:

  • ‘abbcbcb’.rstrip(‘cb’) –> ‘a’
  • ‘abbcbcb’.rstrip(‘cba’) –> ”
  • ‘abbcbcbd’.rstrip(‘cba’) –> ‘abbcbcbd’

Notes: Not just one last character, But it removes the last character repeatedly until a different character is seen.

A. Remove last character from String

Code Thread:

# function to remove the last character using rstrip method
def remove_last_character(string):
    return string.rstrip(string[-1])


# director name with unintended characters like '#'
actual_director_name = 'Martin Scorsese#'

corrected_director_name = remove_last_character(actual_director_name)

print(corrected_director_name)

Output:

Martin Scorsese

B. Remove last n characters from String

Like in the above method A, we can remove the last n character using rstrip() method.

Note: Along with the last n characters, It continuously removes the characters from the right side until a different character than the given parameter characters is encountered.

Code Thread:

# function to remove the last n characters using rstrip() method
def remove_last_n_characters(string, n):
    return string.rstrip(string[-n:])


# director name with unintended characters like '#*'
actual_director_name = 'Martin Scorsese#*'

corrected_director_name = remove_last_n_characters(actual_director_name,2)

print(corrected_director_name)

Output:

Martin Scorsese

5. Using a loop and a new string

This approach is a straightforward one, we used a for loop and a new string.

With for loop, we traverse from 0 to len(string)-1 to skip adding the last character to a new string and return the new string once the loop ends.

A. Remove last character from String

Code Thread:

# function to remove the last character using loop and a new string
def remove_last_character(string):
    # new_string is a new string where we will store string without last_character
    new_string = ""

    # iterate through string from 0 to len(string) - 1
    for i in range(0,len(string)-1):

        # appending current character to new_string
        new_string = new_string + string[i]

    return new_string


# director name with unintended characters like '_'
actual_director_name = 'George Lucas_'

corrected_director_name = remove_last_character(actual_director_name)

print(corrected_director_name)

Output:

George Lucas

B. Remove last n characters from String

It is the same as removing the last character from a string using a for loop and a new string. The only difference is you traverse from 0 to len(string) -n to leave out the last n characters.

Code Thread:

# function to remove the last n characters using loop and a new string
def remove_last_n_characters(string, n):
    new_string = ""

    # iterate through string from 0 to len(string) - n
    for i in range(0,len(string)-n):

        # appending current character to new_string
        new_string = new_string + string[i]

    return new_string


# director name with unintended characters like '_)'
actual_director_name = 'George Lucas_)'

remove_last_n_characters(actual_director_name, 2)

Output:

George Lucas

6. regex

We can remove the last character from string using the sub() method from re module in Python.

A. Remove last character from String

Code Thread:

import re


# function to remove the last character using regex and re.sub method
def remove_last_character(string):
    regex = '.$'
    return re.sub(regex, '', string)


# director name with unintended characters like '@'
actual_director_name = 'Rian Johnson@'

corrected_director_name = remove_last_character(actual_director_name)

print(corrected_director_name)

Output:

Rian Johnson

Explanation:

  • Step 1: Build regex for matching the last character. The regex is ‘.$’. dot(.) character indicates any one character and the $ symbol indicates the end of the String.
  • Step 2: Pass regex from Step 1 to re.sub() function. The res.sub() function takes below three parameters.
    • regex: string – regex from Step 1
    • replacement/fill value: In our case, it is an empty string, as we want to remove the last character.
    • source string: The actual string from which we want to remove the last character.

B. Remove last n characters from String

Removing the last n characters using regex will be the same as the above method. Except that we need to build regex to match to last n characters.

The regex pattern is ‘.{n}$’. We will have to replace n with the actual number.

Code Thread:

import re


# function to remove the last n characters using regex
def remove_last_n_characters(string, n):
    regex = '.{' + str(n) + '}$'
    return re.sub(regex, '', string)


# director name with unintended characters like '@&'
actual_director_name = 'Rian Johnson@&'

corrected_director_name = remove_last_n_characters(actual_director_name,2)

print(corrected_director_name)

Output:

Rian Johnson

7. list class and join() methods

A. remove last character from String

Code Thread:

# function to remove the last character using list class , pop() and join methods
def remove_last_character(string):
    string_list = list(string)

    # pop element removes the last element from the last
    string_list.pop()

    return "".join(string_list)


# director name with unintended characters like '^'
actual_director_name = 'Christopher Nolan^'

corrected_director_name = remove_last_character(actual_director_name)

print(corrected_director_name)

Output:

Christopher Nolan

Explanation:

In this approach, we have used list() constructor and join() method. Below are the step by step details for the input ‘Christopher Nolan^’.

  • Step 1: Create a list object with a string as a parameter.
    • The input ‘Christopher Nolan^’ will be split into a list of individual characters. [‘C’, ‘h’, ‘r’, ‘i’, ‘s’, ‘t’, ‘o’, ‘p’, ‘h’, ‘e’, ‘r’, ‘ ‘, ‘N’, ‘o’, ‘l’, ‘a’, ‘n’, ‘^’]
  • Step 2: Call the pop() method on the list of characters. The pop() method removes the last character from the list.
    • The list of characters after this step will be [‘C’, ‘h’, ‘r’, ‘i’, ‘s’, ‘t’, ‘o’, ‘p’, ‘h’, ‘e’, ‘r’, ‘ ‘, ‘N’, ‘o’, ‘l’, ‘a’, ‘n’]
  • Step 3: Concatenate all the characters back into the string using the join() method
    • The output will be ‘Christopher Nolan’

B. Remove last n characters from String

Removing last n characters is similar to removing the last character from the string. Here in this method, we call pop() method of list object for n times to remove n last characters.

Code Thread:

# function to remove the last n characters using list class and join() methods
def remove_last_n_characters(string, n):
    string_list = list(string)


# calling pop() method for n times to remove the last n elements from the last.
    for i in range(0,n):
        string_list.pop()

    return "".join(string_list)


# director name with unintended characters like '^*'
actual_director_name = 'Christopher Nolan^*'

corrected_director_name = remove_last_n_characters(actual_director_name,2)

print(corrected_director_name)

Output:

Christopher Nolan

How to Remove Last Word from String in Python

In the above sections, We have seen how to remove the last character from the string. In this section, We will see how to remove the last word from a string in Python.

Following are the steps to Remove the last word from String:

Input: sentence = Christopher Nolan

  • Step 1: Split the sentence into words using a space delimiter.
    • The above sentence will be split to [‘Christopher’, ‘Nolan’]
  • Step 2: Remove the last word with the slicing operator and negative indexing.
    • The output after this step will be [‘Christopher’]
  • Step 3: With the join() method, concatenating words again into one sentence.
    • The final result after step 3 is ‘Christopher’.

Code Thread:

def remove_last_word(sentence):
    return "".join(sentence.split()[:-1])


director_name = "Christopher Nolan"
director_name = remove_last_word(director_name)

print(director_name)

Output:

Christopher

Frequently Asked Questions

  • How do you remove the last character of a string in Python?

    To remove the last character from String in Python, we can make use of indexing and slicing concepts. Have explained 5 ways to remove the last character and last N character from a String with complete code examples.

  • How do you trim the last 3 characters of a string?

    To trip last 3 characters of a string in Python, we can use Indexing and slicing along with some in-built functions to handle it in Python. Complete code examples given in this blog post.

Hope we are able to help you with Python Remove Last Character from String explained in different ways. For more such insightful stories, follow CodeThreads.

Leave a Comment

Your email address will not be published. Required fields are marked *