English English French French Spanish Spanish German German
Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

How to Remove Last Character from Python String?

python hosting
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Check out different ways to remove the last character from the string in Python

Slicing

Python supports negative index slicing along with positive slicing. Negative index starts from -1 to -(iterable_length). We will use the negative slicing to get the elements from the end of an iterable.

  • The index -1 gets you the last element from the iterable.
  • The index -2 gets you the 2nd last element from the iterable.
  • And it continuos till the first element.

Let’s see an example.

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

The above program will print the last and first characters from the string using negative indexing.

How do we remove the last element from the string using slicing? It’s just a line of code. We know how to extract a part of the string using slicing. Let’s apply the same thing with a negative index to remove the last character from the string.

  • Slice the string from start to the last before element.
buggy_name = 'GeekflareE'
name = buggy_name[:-1]
print(name)

Let’s focus on the second line in the above code. That’s the magic line in the code. As a traditional slicing, it extracts the substring from the starting index to last but one as slicing ignores the second index element given.

You will get Geekflare as output if you run the above code.

rstrip

The string method rstrip removes the characters from the right side of the string that is given to it. So, we can use it to remove the last element of the string. We don’t have to write more than a line of code to remove the last char from the string.

  • Give the last element to the strip method, it will return the string by removing the last character.

Let’s see the code snippet.

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

We have given the last character of the string to the strip method. It removes the last character from the string and returns a copy without the last character.

It will print Geekflare in the console, if you execute it.

Practical Example – remove the last word

Yeah, we are going to apply what we have in the previous sections in a practical example.

Let’s say we have a file that contains multiple lines of text. And we need to remove the last word from each line in the file.

Follow the below steps to write the program.

  • Create a file called random_text.txt and page a few lines of text in it.
  • Initialize a data variable as an empty string.
  • Open the file using with and open method in read and write mode.
  • Read the content of the file using the readlines method.
  • Iterate over each line of the content.
    • Split the line of text using the split method in words.
    • Remove the last word using one of the above methods.
    • Join the result to form a string.
    • Append the result to the data variable.
  • Remove the data from the file using seek and truncate methods.
  • Write the latest data to the file using write method.

The file contains the following data.

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.

See the code below.

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)

If you execute the above code with the given file, then the file will have the following updated data.

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.

Hope you enjoyed the tutorial.

Happy coding 🙂

Also check Substring Operations in Python.

Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Semrush is an all-in-one digital marketing solution with more than 50 tools in SEO, social media, and content marketing.
    Try Semrush
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder