• How to remove special characters from string Python

    Remove Special Characters from string Python

    In this tutorial, we will be solving a program for how to remove special characters from string Python

    We will be solving the above problem statement in 4 different ways.

    Method 1 – Using isalmun() method

    Python isalnum() return True if all the characters in the string are alphanumeric. Alphanumeric characters meaning the character can alphabet(a-z) or it can be a number(0-9). And it returns false if a string contains the non-alphanumeric character such as @, !, #, $, %, &, space, etc.

    Example:

    s = "TheProblemSeeker10"
    print(s.isalnum())
    Output: True
    
    Because the string 's' does not contain any non-alphanumeric values.

    Steps to remove special characters from String Python

    1. Take input from the user or define the string from which you want to remove the special characters.
    2. Define a new empty string named “final_string” to store the alphanumeric characters.
    3. Apply for loop to access each character in the string and check the character is alphanumeric by using the isalnum() method.
    4. If the character is alphanumeric concatenate that to our new string “final_string”.
    5. End For Loop

    Python Program

    #define input string
    input_string = "The Problem [email protected]"
    final_string = "" #define string for ouput
    for character in input_string:
        if(character.isalnum()):
            # if character is alphanumeric concat to final_string
            final_string = final_string + character
    print("Sample String:", input_string)
    print("Final String:", final_string)

    Output:
    Original String: The Problem [email protected]
    Final String: TheProblemSeeker10

    Method 2 – Using replace() method​

    The approach of this method is to find the special characters using the loop and replace them with a blank string.

    Python Program 

    #define input string
    sample_string = "The Problem [email protected]"
    
    #define special characters list
    special_characters = ['!','#','$','%', '&','@','[',']',' ',']','_']
    
    #print input sample string 
    print("Original String:", sample_string)
    
    #using for loop and replace to remove special characters
    for i in special_characters:
        sample_string = sample_string.replace(i,'')
        
    # print final sample string    
    print("Final String:",sample_string)

    Output:
    Original String: The Problem [email protected]
    Final String: TheProblemSeeker10

    Method 3 – Using filter()

    Another way to remove special characters from string is by using the filter function and lambda function. 

    Python Program

    #define input string
    sample_string = "The Problem [email protected]"
    
    #define special characters list
    special_characters = ['!','#','$','%', '&','@','[',']',' ',']','_']
    
    #print input sample string 
    print("Original String:", sample_string)
    
    # lambda and join function
    sample_string = ''.join(filter(lambda i:i not in special_characters, sample_string))
        
    # print final sample string    
    print("Final String:",sample_string)

    Output:
    Original String: The Problem [email protected]
    Final String: TheProblemSeeker10

    Method 4 – Using join + generator function

    In the generator function we specify the logic that will help us to ignore the special characters from the string and then we remake the string using the join() method.

    Python Program

    #define input string
    sample_string = "The Problem [email protected]"
    
    #define special characters list
    special_characters = ['!','#','$','%', '&','@','[',']',' ',']','_']
    
    #print input sample string 
    print("Original String:", sample_string)
    
    # lambda and join function
    sample_string = ''.join(filter(lambda i:i not in special_characters, sample_string))
        
    # print final sample string    
    print("Final String:",sample_string)

    Output:
    Original String: The Problem [email protected]
    Final String: TheProblemSeeker10

    How to remove special characters from String Python Except Space

    Sometimes we need space in our string but not special characters, we can do that by following methods.

    Method 1 – Using isalnum()

    Here as well we will be using isalnum() but in this, we will check the space character and concatenate with the final string.

    Steps to remove special characters from String Python Except Space are

    1. Take input from the user or define the string from which you want to remove the special characters.
    2. Define a new empty string named “final_string” to store the alphanumeric characters.
    3. Apply for loop to access each character in the string and check whether the character is  space or not
    4. If the character is space, concatenate it to “final_string”
    5. If not space then check the character is alphanumeric by using isalnum() method.
    6. If the character is alphanumeric concatenate that to our new string “final_string”.
    7. End For loop

    Python Program

    input_string = "The Problem [email protected]"
    final_string = ""
    for character in input_string:
        if  character == " ":
         #checking charcter is space and if yes concat
            final_string = final_string + character
        else:
            if(character.isalnum()):
                final_string = final_string + character
    print(final_string)

    Output:
    The Problem Seeker10

    Method 2 – Using Regex Expression

    To remove all special characters from string we can apply a rule using the regex expression. To eliminate the special characters from string regex expression can be defined as [^A-Za-z0-9]+

    To know more about regular expression( regex expression) you read here.

    Python Program

    #importing re model
    import re
    
    #define input string
    sample_string = "The Problem [email protected]"
    
    #print input sample string 
    print("Original String:", sample_string)
    
    # using regex expression
    final_string = re.sub('[^A-Za-z0-9]+', '', sample_string)
     
    # print final sample string    
    print("Final String:",sample_string)

    Output:
    Original String: The Problem [email protected]

    Final String: The Problem Seeker10

    Conclusion

    In this way, by using isalnum(), replace() methods we can remove special characters from string python including space.

    We have also seen how to remove special characters python except for space by using the regex expression and isalnum() method.

    About Author
    Siddhesh Jadhav

    I am Passionate Computer Engineer. Writing articles about programming problems and concepts allows me to follow my passion for programming and helping others.