HomeTechHow to Remove Last Character from Python String?

How to Remove Last Character from Python String?

This article provides several experiments with various Python methods for omitting the last character in a string.

Table of Contents hide

Slicing

Python not only allows positive index slicing but also encourages negative index slicing. From -1 to -(iterable length), negative indices are used. To retrieve data after an iteration, we’ll employ negative slicing.

  • To access the very last item in an iterable, use the index -1.
  • The index -2 ends up getting you the 2nd last element from the iterable.
  • Additionally, it persists till the first constituent.

Here’s an example!

name = 'Geekflare'
print(name[-1])
print(name[-len(name)])

In the preceding code, by utilizing a negative index, we are able to print the string’s end and beginning.

Using slicing, how do we get rid of the last item in the string? Only one line of code is involved. By slicing, we can successfully remove a section of the string. To get rid of the final character in the string, we can use the same technique but this time with a negative index.

Cut the string in half from the beginning to the end of the before elements.

buggy_name = 'GeekflareE'
name = buggy_name[:-1]
print(name)

Let’s examine the second line of code in that example. The crucial line of code is right there. Since the second element of the index is disregarded by slicing, the substring that is extracted spans from the beginning of the string to the last but one character.

When you run the preceding code, you’ll see the term “Geekflare” displayed.

rstrip

The string method rstrip strips the string of characters starting at the right end. Consequently, it can be used to eliminate the last character in a string. To get rid of the final character in the string, we need to write a single line of code.

To get rid of the last character in a string, pass it to the strip method, which will then return the string to you. Let’s see the code snippet.

buggy_name = 'GeekflareE'
name = buggy_name.rstrip(buggy_name[-1])
print(name)

This is the last character of the string, and we’ve passed it on to the strip procedure. It returns a copy of the string sans the final character and removes it.

If you run it, the console will display “Geekflare.”

Take this practical example: drop the last word.

Yes, we will now use the information presented in the preceding chapters to solve a real-world problem.

Let’s pretend we have a document with several paragraphs of text. In addition, we must delete the final character of every line in the document.

To write the software, please refer to the instructions below.

  • Make a text file called random_text.txt and copy and paste a few lines of text into it.
  • Put a blank string into a data variable upon startup.
  • In read-write mode, open the file with the with and open methods.
  • Utilize readlines to examine the data in the file.
  • Read the information line by line.
  1. Cut the line up into words using the split method.
  2. You can get rid of the final word by utilizing any of the strategies above.
  3. Concatenate the final values to create a string.
  4. Add the final tally to the existing data.
  • Using seek and truncate, erase the information from the file.
  • Use the write method to save the most recent changes to the file.

Following is the information that may be found in the file.

This is a sample line for testing. LastWord.
This is a sample line for testing. KillingIt.
This is a sample line for testing. RandomWord.
This is a sample line for testing. DeleteIt.
This is a sample line for testing. RemovingIt.

Here is the source code, if you’re interested.

updated_data = ''

# opening the file
with open('random_text.txt', 'r+') as file:
    # read the file content
    file_content = file.readlines()

    # iterate over the content
    for line in file_content:

        # removing last word
        updated_line = ' '.join(line.split(' ')[:-1])

        # appending data to the variable
        updated_data += f'{updated_line}\n'

    # removing the old data
    file.seek(0)
    file.truncate()

    # writing the new data
    file.write(updated_data)

The following changes will be made to the given file if the preceding code is applied to it.

This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.

I trust the tutorial was helpful. I wish you the best of luck with your programming.

Must Read

Related News