- How to Remove Last Character from Python String?
- Slicing
- rstrip
- Practical Example – remove the last word
- Python remove last symbol in string
- # Remove first and last characters from a String in Python
- # Only removing the first character from the String
- # Only removing the last character from the String
- # Remove first and last characters from a String using strip()
- # Remove first and last characters from String using removeprefix() and removesuffix()
- # Additional Resources
How to Remove Last Character from Python String?
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.
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.
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.
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.
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'\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.
Python remove last symbol in string
Last updated: Feb 20, 2023
Reading time · 3 min# Remove first and last characters from a String in Python
Use string slicing to remove the first and last characters from a string, e.g. result = my_str[1:-1] .
The new string will contain a slice of the original string without the first and last characters.
Copied!my_str = 'apple' # ✅ Remove the first and last characters from a string result_1 = my_str[1:-1] print(result_1) # 👉️ 'ppl' # ✅ Remove the first character from a string result_2 = my_str[1:] print(result_2) # 👉️ 'pple' # ✅ Remove the last character from a string result_3 = my_str[:-1] print(result_3) # 👉️ 'appl'
We used string slicing to remove the first and last characters from a string.
The syntax for string slicing is my_str[start:stop:step] .
Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(my_str) — 1 .
The slice my_str[1:-1] starts at the character at index 1 and goes up to, but not including the last character in the string.
Copied!my_str = 'apple' result_1 = my_str[1:-1] print(result_1) # 👉️ 'ppl'
# Only removing the first character from the String
If you only need to remove the first character from the string, start at index 1 and go til the end of the string.
Copied!my_str = 'apple' result = my_str[1:] print(result) # 👉️ 'pple'
When the stop index is not specified, the slice goes to the end of the string.
# Only removing the last character from the String
If you only need to remove the last character from the string, omit the start index and specify a stop index of -1 .
Copied!my_str = 'apple' result = my_str[:-1] print(result) # 👉️ 'appl'
When the start index is not specified, the slice starts at index 0 .
The slice in the example goes up to, but not including the last character in the string.
# Remove first and last characters from a String using strip()
Alternatively, you can use the str.lstrip() and str.rstrip() methods to remove characters from the start and end of the string.
Copied!my_str = 'apple' result_1 = my_str.lstrip('a').rstrip('e') print(result_1) # 👉️ 'ppl' result_2 = my_str.lstrip('a') print(result_2) # 👉️ 'pple' result_3 = my_str.rstrip('e') print(result_3) # 👉️ 'appl' # ✅ access string at index to not hard-code the characters result_4 = my_str.lstrip(my_str[0]).rstrip(my_str[-1]) print(result_4) # 👉️ 'ppl'
The str.lstrip method takes a string containing characters as an argument and returns a copy of the string with the specified leading characters removed.
The str.rstrip method takes a string containing characters as an argument and returns a copy of the string with the specified trailing characters removed.
The methods do not change the original string, they return a new string. Strings are immutable in Python.
You can access the string at index 0 and index -1 to not have to hard-code the characters.
Copied!my_str = 'apple' result = my_str.lstrip(my_str[0]).rstrip(my_str[-1]) print(result) # 👉️ 'ppl'
They remove all occurrences and combinations of the specified character from the start or end of the string.
Copied!my_str = 'aaappleeee' result_1 = my_str.lstrip('a').rstrip('e') print(result_1) # 👉️ 'ppl' result_2 = my_str.lstrip('a') print(result_2) # 👉️ 'ppleeee' result_3 = my_str.rstrip('e') print(result_3) # 👉️ 'aaappl'
# Remove first and last characters from String using removeprefix() and removesuffix()
Alternatively, you can use the str.removeprefix() and str.removesuffix() methods.
Copied!my_str = 'apple' result_1 = my_str.removeprefix('a').removesuffix('e') print(result_1) # 👉️ 'ppl' result_2 = my_str.removeprefix('a') print(result_2) # 👉️ 'pple' result_3 = my_str.removesuffix('e') print(result_3) # 👉️ 'appl'
The str.removeprefix method checks if the string starts with the specified prefix and if it does, the method returns a new string excluding the prefix, otherwise, it returns a copy of the original string.
The str.removesuffix method checks if the string ends with the specified suffix and if it does, the method returns a new string excluding the suffix, otherwise, it returns a copy of the original string.
The difference between str.lstrip and str.removeprefix is that the str.lstrip method removes all combinations of the specified characters, whereas the str.removeprefix method removes only the specified prefix.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.