Delete last char in string python

Remove last N characters from string in Python

In this article we will discuss different ways to delete last N characters from a string i.e. using slicing or for loop or regex.

Remove last N character from string by slicing

In python, we can use slicing to select a specific range of characters in a string i.e.

It returns the characters of the string from index position start to end -1, as a new string. Default values of start & end are 0 & Z respectively. Where Z is the size of the string.

It means if neither start nor end are provided, then it selects all characters in the string i.e. from 0 to size-1 and creates a new string from those characters.

Frequently Asked:

We can use this slicing technique to slice out a piece of string, that includes all characters of string except the last N characters. Let’s see how to do that,

Remove last 3 character from string using Slicing & Positive Indexing

Suppose our string contains N characters. We will slice the string to select characters from index position 0 to N-3 and then assign it back to the variable i.e.

org_string = "Sample String" size = len(org_string) # Slice string to remove last 3 characters from string mod_string = org_string[:size - 3] print(mod_string)

By selecting characters in string from index position 0 to N-3, we selected all characters from string except the last 3 characters and then assigned this sliced string back to the same variable again, to give an effect that final 3 characters from string are deleted.

P.S. We didn’t explicitly provided 0 as start index, because its default value is 0. So we just skipped it.

Remove last character from string using Slicing & Positive Indexing

org_string = "Sample String" size = len(org_string) # Slice string to remove last character from string mod_string = org_string[:size - 1] print(mod_string)

By selecting characters in string from index position 0 to size-1, we selected all characters from string except the last character.

The main drawback of positive indexing in slicing is: First we calculated the size of string i.e. N and then sliced the string from 0 to N-1. What if we don’t want to calculate the size of string but still want to delete the characters from end in a string?

Remove last N characters from string Using negative slicing

In python, we can select characters in a string using negative indexing too. Last character in string has index -1 and it will keep on decreasing till we reach the start of the string.

For example for string “Sample”,

Index of character ‘e’ is -1
Index of character ‘l’ is -2
Index of character ‘p’ is -3
Index of character ‘m’ is -4
Index of character ‘a’ is -5
Index of character ‘S’ is -6

So to remove last 3 characters from a string select character from 0 i.e. to -3 i.e.

org_string = "Sample String" # Slice string to remove 3 last characters mod_string = org_string[:-3] print(mod_string)

It returned the a new string built with characters from start of the given string till index -4 i.e. all except last 3 characters of the string. we assigned it back to the string to gave an effect that last 3 characters of the string are deleted.

Читайте также:  Label html что значит

Remove last characters from string Using negative slicing

To remove last character from string, slice the string to select characters from start till index position -1 i.e.

org_string = "Sample String" # Slice string to remove 1 last character mod_string = org_string[:-1] print(mod_string)

It selected all characters in the string except the last one.

Remove final N characters from string using for loop

We can iterate over the characters of string one by one and select all characters from start till (N -1)th character in the string. For example, let’s delete last 3 characters from a string i.e.

org_string = "Sample String" n = 3 mod_string = "" # Iterate over the characters in string and select all except last 3 for i in range(len(org_string) - n): mod_string = mod_string + org_string[i] print(mod_string)

To remove last 1 character, just set n to 1.

Remove Last N character from string using regex

We can use regex in python, to match 2 groups in a string i.e.

  • Group 1: Every character in string except the last N characters
  • Group 2: Last N character of string

Then modify the string by substituting both the groups by a single group i.e. group 1.

For example, let’s delete last 3 characters from string using regex,

import re def remove_second_group(m): """ Return only group 1 from the match object Delete other groups """ return m.group(1) org_string = "Sample String" # Remove final 3 characters from string result = re.sub("(.*)(.$)", remove_second_group, org_string) print(result)

Here sub() function matched the given pattern in the string and passed the matched object to our call-back function remove_second_group(). Match object internally contains two groups and the function remove_second_group() returned a string by selecting characters from group 1 only. Then sub() function replaced the matched characters in string by the characters returned by the remove_second_group() function.

To remove last character from string using regex, use instead,

org_string = "Sample String" # Remove final n characters from string result = re.sub("(.*)(.$)", remove_second_group, org_string) print(result)

It removed the last character from the string

Remove last character from string if comma

It might be possible that in some scenarios we want to delete the last character of string, only if it meets a certain criteria. Let’s see how to do that,

Delete last character from string if it is comma i.e.

org_string = "Sample String," if org_string[-1] == ',': result = org_string[:-n-1] print(result)

So, this is how we can delete last N characters from a string in python using regex and other techniques.

The complete example is as follows,

import re def remove_second_group(m): """ Return only group 1 from the match object Delete other groups """ return m.group(1) def main(): print('***** Remove last character N from string by slicing *****') print('*** Remove Last 3 characters from string by slicing using positive indexing***') org_string = "Sample String" size = len(org_string) # Slice string to remove last 3 characters from string mod_string = org_string[:size - 3] print(mod_string) print('*** Remove Last character from string by slicing using positive indexing***') org_string = "Sample String" size = len(org_string) # Slice string to remove last character from string mod_string = org_string[:size - 1] print(mod_string) print('***** Using negative slicing to remove last N characters from string *****') print('*** Remove Last 3 characters from string by slicing using negative indexing***') org_string = "Sample String" # Slice string to remove 3 last characters mod_string = org_string[:-3] print(mod_string) print('*** Remove Last character from string by slicing using negative indexing***') org_string = "Sample String" # Slice string to remove 1 last character mod_string = org_string[:-1] print(mod_string) print('***** Remove Last N characters from string using for loop *****') org_string = "Sample String" n = 3 mod_string = "" # Iterate over the characters in string and select all except last 3 for i in range(len(org_string) - n): mod_string = mod_string + org_string[i] print(mod_string) print('***** Remove Last N character from string using regex *****') print('*** Remove Last 3 characters from string using regex ***') org_string = "Sample String" # Remove final 3 characters from string result = re.sub("(.*)(.$)", remove_second_group, org_string) print(result) print('*** Remove last character from string using regex ***') org_string = "Sample String" # Remove final n characters from string result = re.sub("(.*)(.$)", remove_second_group, org_string) print(result) print('***** Remove last character from string if comma *****') org_string = "Sample String," if org_string[-1] == ',': result = org_string[:-1] print(result) if __name__ == '__main__': main()
***** Remove last character N from string by slicing ***** *** Remove Last 3 characters from string by slicing using positive indexing*** Sample Str *** Remove Last character from string by slicing using positive indexing*** Sample Strin ***** Using negative slicing to remove last N characters from string ***** *** Remove Last 3 characters from string by slicing using negative indexing*** Sample Str *** Remove Last character from string by slicing using negative indexing*** Sample Strin ***** Remove Last N characters from string using for loop ***** Sample Str ***** Remove Last N character from string using regex ***** *** Remove Last 3 characters from string using regex *** Sample Str *** Remove last character from string using regex *** Sample Strin ***** Remove last character from string if comma ***** Sample String

Источник

Читайте также:  Python get dir name

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.
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.
Читайте также:  Построить корреляционную матрицу python

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.

    Источник

Оцените статью