Python remove multiple characters from string by index

In this article we will discuss how to remove characters from a string at specific index position or in a given range of indices.

We can remove characters from string by slicing the string into pieces and then joining back those pieces.

String Slicing

In Python strings are immutable i.e. we can not modify the string objects. Therefore when we slice a string it returns a new string object instead of modifying then original one.

We can slice a string using operator [] i.e.

stringObject[ start : stop : interval]

It returns a new string object containing parts of given string i.e. it selects a range from start to stop-1 with given step size i.e. interval.

Advertisements

Let’s use slicing to remove characters from a string by index.

Remove a character from string at specific index

Suppose we have a string object i.e.

strObj = "This is a sample string"

Let’s remove the character at index 5 in above created string object i.e.

index = 5
# Slice string to remove character at index 5
if len[strObj] > index:
    strObj = strObj[0 : index : ] + strObj[index + 1 : :]

Output:

Modified String :  This s a sample string

It deleted the character at index 5 i.e. ‘i’ from ‘is’ in the above string.

As we can not modify the immutable string objects, so to simulate the removal effect we just selected the sub string from index [0 to index] & [index+1 to end], then merged those sub strings and assigned it back to the original string.  Cheeky trick 😉

Now let’s use the same trick to achieve other things i.e.

Remove First Character from a String

Just select the range from index 1 to end and assign it back to original string i.e.

strObj = "This is a sample string"

# Slice string to remove first character
strObj = strObj[1 : : ]

print['Modified String : ' , strObj]

Output:

Modified String :  his is a sample string

Remove Last Character from a String

Just select the range from index 0 to end – 1 and assign it back to original string i.e.

strObj = "This is a sample string"

# Slice string to remove last character
strObj = strObj[:-1:]

Output:

Modified String :  This is a sample strin

Remove multiple characters from a string in given index range

We can use the same trick to delete the multiple characters from a given string for a given index range.

For example let’s see how to delete the characters in index range 5 to 10 from a given string i.e.

strObj = "This is a sample string"

start = 5
stop = 10
# Remove charactes from index 5 to 10
if len[strObj] > stop :
    strObj = strObj[0: start:] + strObj[stop + 1::]

Output:

Modified String :  This ample string

Complete example is as follows :

def main[]:

   print['*** Remove character at specific index ***']

   strObj = "This is a sample string"

   index = 5
   # Slice string to remove character at index 5
   if len[strObj] > index:
       strObj = strObj[0 : index : ] + strObj[index + 1 : :]

   print['Modified String : ', strObj]

   print['*** Remove first character ***']

   strObj = "This is a sample string"

   # Slice string to remove first character
   strObj = strObj[1 : : ]

   print['Modified String : ' , strObj]

   print['*** Remove Last character ***']

   strObj = "This is a sample string"

   # Slice string to remove last character
   strObj = strObj[:-1:]

   print['Modified String : ', strObj]


   print['*** Remove multiple characters at index range***']


   strObj = "This is a sample string"

   start = 5
   stop = 10
   # Remove charactes from index 5 to 10
   if len[strObj] > stop :
       strObj = strObj[0: start:] + strObj[stop + 1::]

   print['Modified String : ', strObj]


if __name__ == '__main__':
   main[]

Output:

*** Remove character at specific index ***
Modified String :  This s a sample string
*** Remove first character ***
Modified String :  his is a sample string
*** Remove Last character ***
Modified String :  This is a sample strin
*** Remove multiple characters at index range***
Modified String :  This ample string

 

In this article, we will discuss four different ways to delete multiple characters from a string in python.

Suppose we have a string “A small sample String for testing” and a list of characters that need to be deleted from string i.e.

list_of_chars = ['s', 't', 'a', 'A', ' ']

Let’s see how to delete these characters from the string.

Delete multiple characters from string using translate[] function

The string class in python, provides a function translate[]. It accepts a translation table as an argument and replaces the characters in string based on the mapping in the translation table. We can create a translation table, where each character that we want to be deleted from string, will be mapped to an empty string. Like,

  • Ascii value of ‘s’ : ”
  • Ascii value of ‘t’ : ”
  • Ascii value of ‘a’ : ”
  • Ascii value of ‘A’ : ”
  • Ascii value of ‘ ‘ : ”

We will pass this translation table to translate[] function as an argumment. Due to which translate[] function will replace all the occurrences of these characters with an empty string. Basically it will remove all the occurrences of these characters from the string. For example,

Advertisements

sample_str = 'A small sample String for testing'

# A list containing multiple characters, that needs to be deleted from the string.
list_of_chars = ['s', 't', 'a', 'A', ' ']

# Create a mapping table to map the characters 
# to be deleted with empty string
translation_table = str.maketrans['', '', ''.join[list_of_chars]]

# Remove multiple characters from the string
sample_str = sample_str.translate[translation_table]

print[sample_str]

Output:

mllmpleSringforeing

It removed all occurrences of multiple characters from the string.

Delete multiple characters from string using regex

In Python, the regex module provides a function to replace the contents of a string based on a matching regex pattern. Signature of function is like this,

sub[pattern, replacement_str, original_str]

We can use this to remove multiple characters from a string. For this we need to pass a regex pattern that matches all the occurrences of the given characters. Also, as a replacement string we need to pass a empty string. For example, let’s see how to delete characters ‘s’, ‘t’, ‘a’, ‘A’ and ‘ ‘ from a string using regex,

import re

sample_str = 'A small sample String for testing'

# A list containing multiple characters, that needs to be deleted from the string.
list_of_chars = ['s', 't', 'a', 'A', ' ']

# Create regex pattern to match all characters in list
pattern = '[' +  ''.join[list_of_chars] +  ']'

# Remove multiple characters from the string
sample_str = re.sub[pattern, '', sample_str]

print[sample_str]

Output:

mllmpleSringforeing

It removed all occurrences of ‘s’, ‘t’, ‘a’, ‘A’ and ‘ ‘ from the string.

Delete multiple characters from string using replace[]

The string class provides a function to replace a sub-string in a string i.e.

str.replace[to_be_replaced, replacement]

It accepts two arguments i.e. the string to be replaced and the replacement string. It returns a copy of the calling string object but with the changed contents i.e. after replacing all the occurrences of sub-string to_be_replaced with the given replacement string. So, to delete multiple characters from a string using replace[] function, follow this logic:

Iterate over all the characters to be deleted and for each character, pass it to the replace[] function along with the empty string. For example,

sample_str = 'A small sample String for testing'

# A list containing multiple characters, that needs to be deleted from the string.
list_of_chars = ['s', 't', 'a', 'A', ' ']

# Remove multiple characters from the string
for character in list_of_chars:
    sample_str = sample_str.replace[character, '']

print[sample_str]

Output:

mllmpleSringforeing

It removed all occurrences of multiple characters i.e. ‘s’, ‘t’, ‘a’, ‘A’ and ‘ ‘ from the string.

Delete multiple characters from string using filter[] and join[]

In Python, you can use the filter[] function to filter all the occurences of a characters from a string. Steps are as follows,

  • Create a lambda function, that accepts a character as an argument and returns True only if the passed character matches with any of the given the characters that need to be deleted.
  • Along with the string to be modified, pass the above created lambda function to the filter[] function, as the conditional argument.
  • filter[] function loops through all characters of string and yields only those characters for which lambda function returns True i.e. all characters except the characters that need to be deleted.
  • Use join[] function to combine all yielded characters returned by filter[] function.
  • Assign back the joined string returned by join[] function to the original variable. It will give an effect that we have deleted multiple characters from the string.

For example,

sample_str = 'A small sample String for testing'

# A list containing multiple characters, that needs to be deleted from the string.
list_of_chars = ['s', 't', 'a', 'A', ' ']

# Filter multiple characters from string
filtered_chars = filter[lambda item: item not in list_of_chars, sample_str]

# Join remaining characters in the filtered list
sample_str = ''.join[filtered_chars]

print[sample_str]

Output:

mllmpleSringforeing

Summary:

We learned about different ways to delete multiple characters from a string in python.

How do I remove multiple characters from a string in Python?

To remove multiple characters from a string we can easily use the function str. replace and pass a parameter multiple characters. The String class [Str] provides a method to replace[old_str, new_str] to replace the sub-strings in a string. It replaces all the elements of the old sub-string with the new sub-string.

How do I remove a character from a string using index?

The str. replace[] can possibly be used for performing the task of removal as we can replace the particular index with empty char, and hence solve the issue.

How do I remove a specific index from a string in Python?

Use string slicing to remove a character from a string by index, e.g. result = my_str[:idx] + my_str[idx+1:] . The first slice returns the part of the string before the specified index, and the second slice - the part of the string after the specified index.

How do I remove multiple elements from a string?

Remove Multiple Characters from a String in Python.
Using nested replace[].
Using translate[] & maketrans[].
Using subn[].
Using sub[].

Chủ Đề