Remove given characters from a string in Python

Sometimes a programmer may face problems regarding unwanted characters in a string. The generic problem occurs when we download a file so the file data can have some unwanted characters or strings present in it. This tutorial will help you learn how to remove given characters from a string in Python with the help of different methods. So, read the tutorial very carefully to clear all your doubts.

Using replace()

The replace() method in Python is one of the methods that can be used to remove specific characters from a string based on the given characters. Use str.replace() function inside the loop to check the unwanted characters and then replace those with an empty string. In this method, the first approach is to initialize the unwanted characters in a list and then initialize the test string. After this use the replace function in the loop to remove the unwanted characters from a string. Follow the code given below to clear your doubts.

# initializing unwanted_list
unwanted_char = [';', ':', '!', "*", " "]
 
# initializing test string
test_string = "co*d!e;;sp e e*d:y"
 
# print the original string
print("Original String : " + test_string)
 
# using replace() to
# remove unwanted_char
for i in unwanted_char:
    test_string = test_string.replace(i, '')
 
# print the resultant string
print("Resultant list is : " + str(test_string))

Output:

Original String : co*d!e;;sp e e*d:y
Resultant list is : codespeedy

Using Python join() + generator to remove given characters from a string

join()+ generator is another method to remove the given characters from a string in Python. In this method, the first step is to initialize the list of unwanted characters and a test string then use join()+ generator function in the test string to remove unwanted characters and at last print the resultant string. The whole method is explained with the code given below:

# initializing the unwanted_chars in a list
unwanted_chars = [';', ':', '!', "*", " "]

# initialize the test string
test_string = "co*d;e  s**p:ee d;y"

# print the original string
print("Original String : " + test_string)

# using join() + generator function to remove unwanted_chars
test_string = ''.join(i for i in test_string if not i in unwanted_chars)

# print the resultant string
print("Resultant list is : " + str(test_string))

Output:

Original String : co*d;e  s**p:ee d;y
Resultant list is : codespeedy

Also read: Replace space with underscore in Python

Leave a Reply

Your email address will not be published. Required fields are marked *