Python Program to Remove Special Characters From the String

Python program to remove special characters from string; Through this tutorial, i am going to show you how to remove special characters from string in python.

How to Remove Special Characters From the String in Python

I will use python method replace(), join() and filter() to remove special characters from string in python; as shown below:

  • 1: Remove special characters from string in python using replace()
  • 2: Remove special characters from string in python using  join() + generator
  • 3: Remove special characters from string in python using  Using filter()

1: Remove special characters from string in python using replace()

# Python code to remove special char
# using replace() 
  
# initializing special characters 
sp_chars = [';', ':', '!', "*"] 
  
# given string  
givenStr = "Hel;lo *w:o!r;ld * de*ar !"
  
# print given string
print ("Original String : " + givenStr) 
  
# using replace() to  
# remove special chars  
for i in sp_chars : 
    givenStr = givenStr.replace(i, '') 
  
# printing resultant string  
print ("After Remove special char : " + str(givenStr)) 

After executing the program, the output will be:

Original String : Hel;lo *w:o!r;ld * de*ar !
After Remove special char : Hello world  dear

2: Remove special characters from string in python using  join() + generator

# Python code to remove special char
# using join() + generator 
  
# initializing special characters 
sp_chars = [';', ':', '!', "*"] 
  
# given string  
givenStr = "Hel;lo *w:o!r;ld * de*ar !"
  
# print given string
print ("Original String : " + givenStr) 
  
# using join() + generator to  
# remove special chars  
givenStr = ''.join(i for i in givenStr if not i in sp_chars) 
  
# printing resultant string  
print ("After Remove special char : " + str(givenStr)) 

After executing the program, the output will be:

Original String : Hel;lo *w:o!r;ld * de*ar !
After Remove special char : Hello world  dear

3: Remove special characters from string in python using  Using filter()

# Python code to remove special char
# using filter() 
  
# initializing special characters 
sp_chars = [';', ':', '!', "*"] 
  
# given string  
givenStr = "Hel;lo *w:o!r;ld * de*ar !"
  
# print given string
print ("Original String : " + givenStr) 
  
# using filter() to  
# remove special chars 
givenStr = filter(lambda i: i not in sp_chars, givenStr) 
  
# printing resultant string  
print ("After Remove special char : " + str(givenStr)) 

After executing the program, the output will be:

Original String : Hel;lo *w:o!r;ld * de*ar !
After Remove special char : Hello world  dear

Recommended Python Tutorials

Leave a Comment