Python delete last symbol in string

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.

Читайте также:  Php open file in memory

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.

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

Работа со строками в Python — одна из самых частых задач, которые ставятся перед программистами. Одной из особенностей работы со строками является неизменяемость строк в Python. Это означает, что нельзя просто так взять и изменить один символ в уже существующей строке. Но что если требуется удалить последний символ из строки?

Допустим, есть строка «Привет, мир!». И требуется преобразовать её в «Привет, мир». Как это сделать в Python?

Способ 1: Использование срезов строк

Один из самых простых и эффективных способов — использование срезов строк. В Python можно «срезать» нужную часть строки, указав начало и конец среза.

В данном случае, чтобы удалить последний символ, нужно сделать срез от начала строки до предпоследнего символа. Это делается очень просто — нужно указать в квадратных скобках индекс первого символа (в данном случае, это 0, так как индексация в Python начинается с нуля), двоеточие и индекс последнего символа.

s = "Привет, мир!" s_new = s[:-1] print(s_new) # Выведет: "Привет, мир"

Способ 2: Использование метода rstrip()

Еще один способ — использование метода rstrip(). Этот метод удаляет указанные символы справа от строки.

s = "Привет, мир!" s_new = s.rstrip("!") print(s_new) # Выведет: "Привет, мир"

Однако, стоит учесть, что этот метод удаляет все указанные символы, находящиеся справа, а не только последний. Если в конце строки несколько одинаковых символов, которые нужно удалить, то этот метод подойдет идеально. В противном случае лучше использовать срезы.

Таким образом, удалить последний символ из строки в Python можно двумя способами — с помощью срезов и с помощью метода rstrip(). Выбор способа зависит от конкретной ситуации.

Источник

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