Python | Remove all characters except letters and numbers

Given a string, the task is to remove all the characters except numbers and alphabets.

String manipulation is a very important task in a day to day coding and web development. Most of the request and response in HTTP queries are in the form of strings with sometimes some useless data which we need to remove. Let’s discuss some Pythonic ways to remove all the characters except numbers and alphabets.

Method #1: Using re.sub



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# to remove all the characters
# except numbers and alphabets
  
import re
  
# initialising string
ini_string = "123abcjw:, .@! eiw"
  
# printing initial string
print ("initial string : ", ini_string)
  
# function to demonstrate removal of characters
# which are not numbers and alphabets using re
  
result = re.sub('[\W_]+', '', ini_string)
  
# printing final string
print ("final string", result)

chevron_right


Output:

initial string :  123abcjw:, .@! eiw
final string 123abcjweiw

 
Method #2: Using isalpha() and isnumeric()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# to remove all the characters
# except numbers and alphabets
  
import re
  
# initialising string
ini_string = "123abcjw:, .@! eiw"
  
# printing initial string
print ("initial string : ", ini_string)
  
# function to demonstrate removal of characters
# which are not numbers and alphabets using re
getVals = list([val for val in ini_string
               if val.isalpha() or val.isnumeric()])
  
result = "".join(getVals)
  
# printing final string
print ("final string", result)

chevron_right


Output:

initial string :  123abcjw:, .@! eiw
final string 123abcjweiw

 
Method #3: Using alnum()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# to remove all the characters
# except numbers and alphabets
  
# initialising string
ini_string = "123abcjw:, .@! eiw"
  
# printing initial string
print ("initial string : ", ini_string)
  
# function to demonstrate removal of characters
# which are not numbers and alphabets using re
getVals = list([val for val in ini_string if val.isalnum()])
result = "".join(getVals)
  
# printing final string
print ("final string", result)

chevron_right


Output:

initial string :  123abcjw:, .@! eiw
final string 123abcjweiw


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.