Program to remove all characters except letters and numbers

Introduction

The task is to remove all the characters from the given string except letters and numbers. As developers while dealing with request and response in HTTP queries we may need to remove some useless characters present in it. At that time using python approach will be helpful.

remove all characters

Program

Approach 1

import re 
ip_str = input("Enter the string: ")
# Using re.sub
op_result = re.sub('[\W_]+', '', ip_str) 
print ("Output string is:", op_result)

Output

remove all characters Output 1

Approach 2

import re 
ip_str = input("Enter the string: ")
# Using isalpha() and isnumeric()
ele = list([i for i in ip_str if i.isalpha() or i.isnumeric()]) 
  
op_result = "".join(ele)  
print ("Output string is:", op_result)

Output

remove all characters Output 2

Approach 3

import re 
ip_str = input("Enter the string: ")
# Using isalnum()
ele = list([i for i in ip_str if i.isalnum()]) 
  
op_result = "".join(ele)  
print ("Output string is:", op_result)

Output

remove all characters Output 3

Explanation

We have used three approaches. The first approach is by using re.sub() method. In re.sub() method we have passed three arguments : expression, replace with char and input string. In our code the expression is ‘[\W_]+’ which constitutes chars [a-zA-Z_0-9]. We are deleting all the character except the letters and numbers.

In the second approach, we have formed the list of characters that are alphabets and numeric using isalpha() and isnumeric() methods. In the end, we joined the elements using space delimiter.

In the third approach, we have formed the list of characters that are alphanumeric using isalnum() method and joined the elements using space delimiter.

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.