How to remove a character from a string in python?

Strings are a sequence of characters enclosed within a single or double quote. Sometimes we want to remove certain characters from a string.

For example, "Pro#gram#min#g" represents a string. Removing '#' from the string gives output as 'Programming'. This article discusses several approaches to remove characters from a string in python.

Removing a specific character from a string

A specific character from a string can be removed by using replace(), translate(), or by using for loop.

By using replace() method

The replace() is a built-in method in python, that takes three arguments the old substring, the new substring that would replace the old substring, and the count(optional) which indicates the number of occurrences of the old substring to replace. The replace() method returns a new string with all the old characters replaced with new characters.

The syntax for the replace() function is given below.

#syntax:
string.replace(old,new,count)

Consider string string_1 = "[email protected]@[email protected]" . string_1.replace('@', '') replace '@' with an empty string '' to remove all the occurrence of '@'.

string_1 = "[email protected]@[email protected]"
print("string_1: ", string_1)
string_2 = string_1.replace('@','')
print("string_2: ", string_2)

The above code returns 'Python' as a new string.

string_1:  [email protected]@[email protected]
string_2:  Python
By using translate() method

The translate() function returns a new string by replacing the old substring with a new substring. The translate() function uses a mapping table or a dictionary to represent the old substring and new substring.

We can use the maketrans() function to create a mapping table. If we use a dictionary, then ASCII codes must be used instead of characters.

Example 1: Consider string string_1 = "[email protected]@[email protected]" . We use ord() to get ASCII values of the characters and use 'None' as a value to remove the characters.

string_1 = "[email protected]@[email protected]"
print("string_1: ", string_1)
string_2 = string_1.translate({ord('@'): None})
print("string_2: ", string_2)

The above code returns the output as 'Python'.

string_1:  [email protected]@[email protected]
string_2:  Python

Example 2: Removing white spaces from a string using replace() and translate() method

string_1 = "This is a string"
print("string_1: ", string_1)
string_2 = string_1.replace(' ','')
print("Removing whitespace using replace(): ", string_2)
string_3 = string_1.translate({ord(' '): None})
print("Removing whitespace using translate(): ", string_2)

Output

string_1:  This is a string
Removing whitespace using replace():  Thisisastring
Removing whitespace using translate():  Thisisastring
By using re.sub() method

The re.sub() method can be imported from the re(Regular expressions) module. The re.sub() returns a string by replacing a set of one or more characters with a replacement string. The syntax for re.sub() is given below.

#syntax:
re.sub(pattern, repl, string)
  • pattern: The pattern indicates the set of characters to be replaced.
  • repl: This takes a string as an argument that would replace the characters.
  • string: This represents the original string.

Consider a string string_1 = "[email protected]#t#[email protected]#[email protected]".The re.sub() method takes the pattern as [@#] and the replacement string as an empty string ' '. "[@#]" indicates the characters that will get replaced by replacement string ''. The string_1 is passed as an argument to the actual string.

import re
string_1 = "[email protected]#t#[email protected]#[email protected]"
print("string_1: ", string_1)
string_2 = re.sub("[@#]", '', string_1)
print("string_2: ", string_2)

The above code gives output as

string_1:  [email protected]#t#[email protected]#[email protected]
string_2:  Python
By using For loop

Consider a string string_1 = "[email protected]#t#[email protected]#[email protected]". A variable rep and string_2 are initialized to '@#' and empty string '' respectively. A for loop iterates over the string_1 and checks if each character is present in the substring rep. If it is not present then the character is concatenated with string_2.

string_1 = "[email protected]#t#[email protected]#[email protected]"
print("string_1: ", string_1)
rep = '@#'
string_2 = ''
for i in string_1:
    if i not in rep:
        string_2 += i
print("string_2: ", string_2)

The above code gives output as 'Python'.

string_1:  [email protected]#t#[email protected]#[email protected]
string_2:  Python

Removing all the characters except alphabets from a string

All the characters except alphabets from a string can be removed by using filter(), re.sub(), or by using for loop.

By using filter() method

The filter() method takes two arguments, a function, and a sequence(list, tuple, string, etc). Each element of the sequence is passed as a parameter to the function. The filter constructs an iterator from elements of the sequence for which function returns True. The syntax for the filter() function is

#syntax:
filter(function, sequence)

Consider a string string_1 = "Ch$##erc&*her ^[email protected]". The filter() function takes str.isalpha as a function and string_1 as an iterable. isalpha() checks if the character in the string is an alphabet and returns a boolean value. The join() function joins each element of the iterator return by filter() function and returns the output as ChercherTech.

string_1 = "Ch$##erc&*her ^[email protected]"
print("string_1: ", string_1)
string_2 ="".join(filter(str.isalpha, string_1))
print("string_2: ", string_2)

The above code returns the output as

string_1:  Ch$##erc&*her ^[email protected]
string_2:  ChercherTech
By using re.sub() method

Consider a string string_1 = "Ch$##erc&*her ^[email protected]". The re.sub() method takes the pattern as [^A-za-z] and the replacement string as an empty string ' '. ^ symbol in the pattern represents not. [^A-za-z] indicates characters other than A-Z and a-z will get replaced.

import re
string_1 = "Ch$##erc&*her ^[email protected]"
print("string_1: ", string_1)
string_2 = re.sub("[^A-Za-z]", '', string_1)
print("string_2: ", string_2)

The above code gives the output as ChercherTech.

string_1:  Ch$##erc&*her ^[email protected]
string_2:  ChercherTech
By using for loop

Consider a string string_1 = "Ch$##erc&*her ^[email protected]". A for loop can be used instead of using the filter() method. A for loop iterates over the string_1. At each iteration, it checks if the character is an alphabet by using the isalpha() function. If the character is an alphabet the character is concatenated to string_2.

string_1 = "Ch$##erc&*her ^[email protected]"
print("string_1: ", string_1)
string_2 = ''
for ch in string_1:
    if ch.isalpha():
        string_2 += ch
print("string_2: ", string_2)

Output

string_1:  Ch$##erc&*her ^[email protected]
string_2:  ChercherTech

Removing all the characters except alphabets and numbers from a string

All the characters except alphabets and numbers from a string can be removed by using filter(), re.sub(), or by using for loop.

By using filter() method

Consider a string string_1 = "P#Y^[email protected]$ON3". The filter() function takes str.isalnum as a function and string_1 as an iterable. isalnum() checks if the character in the string is an alphabet or number and returns a boolean value. The join() function joins each element of the iterator return by filter() function and returns the output as "PYTHON3".

string_1 = "P#Y^[email protected]$ON3"
print("string_1: ", string_1)
string_2 ="".join(filter(str.isalnum, string_1))
print("string_2: ", string_2)

Output

string_1:  P#Y^[email protected]$ON3
string_2:  PYTHON3
By using re.sub() method

Consider a string string_1 = "P#Y^[email protected]$ON3" . The re.sub() method takes the pattern as [^A-za-z0-9] and the replacement string as an empty string ' '. [^A-za-z0-9] indicates characters other than A-Z,a-z, and 0-9 will get replaced.

import re
string_1 = "P#Y^[email protected]$ON3"
print("string_1: ", string_1)
string_2 = re.sub("[^A-Za-z0-9]", '', string_1)
print("string_2: ", string_2)

The above code gives the output as PYTHON3.

string_1:  P#Y^[email protected]$ON3
string_2:  PYTHON3

Removing all the characters except numbers from a string

All the characters except numbers from a string can be removed by using filter(), re.sub(), or by using for loop.

By using filter() method

Consider a string string_1 = "123# [email protected]!". The filter() function takes str.isdecimal as a function and string_1 as an iterable. isdecimal() checks if the character in the string is a number and returns a boolean value. The join() function joins each element of the iterator return by filter() function and returns the output as 123678.

string_1 = "123# [email protected]!"
print("string_1: ", string_1)
string_2 ="".join(filter(str.isdecimal, string_1))
print("string_2: ", string_2)

Output

string_1:  123# [email protected]!
string_2:  123678
By using re.sub() method

Consider a string string_1 = "123# [email protected]!" . The res.sub() method takes the pattern as [^0-9] and the replacement string as an empty string ' '. [^0-9] indicates characters other than 0-9 will get replaced.

import re
string_1 = "123# [email protected]!"
print("string_1: ", string_1)
string_2 = re.sub("[^0-9]", '', string_1)
print("string_2: ", string_2)

The above code gives output as 123678.

string_1:  123# [email protected]!
string_2:  123678
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions