The Wayback Machine - https://web.archive.org/web/20250118010344/https://www.geeksforgeeks.org/python-remove-all-characters-except-letters-and-numbers/
Open In App

Python | Remove all characters except letters and numbers

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Objective is to write a program that filters out all characters from a string except for letters (a-z, A-Z) and digits (0-9). The aim is to clean the string by removing special characters, punctuation marks and whitespace, leaving only alphanumeric characters intact.

Using Regular Expressions (re.sub())

re.sub() function in Python is used to search for a pattern in a string and replace it with a specified replacement, which can be useful for modifying or counting spaces using regular expressions.

Python
import re

# Input string
s1 = "Hello, World! 123 @Python$"

# Remove all characters except letters and numbers using regex
s2 = re.sub(r'[^a-zA-Z0-9]', '', s1)

# Print the cleaned string
print(s2)

Output
HelloWorld123Python

Explanation

  • re.sub(r'[^a-zA-Z0-9]', '', s1) function uses a regular expression to find all characters in the string s1 that are not letters (a-zA-Z) or numbers (0-9) and replaces them with an empty string, effectively removing them.
  • cleaned string, which now only contains letters and numbers, is stored in s2and printed.

Using List Comprehension and str.isalnum()

List comprehension combined with str.isalnum() allows us to iterate through each character in a string and keep only those that are alphanumeric (letters and numbers)

Python
# Input string
s1 = "Hello, World! 123 @Python$"

# Use list comprehension to keep only alphanumeric characters
s2 = ''.join([char for char in s1 if char.isalnum()])

# Print the cleaned string
print(s2)

Output
HelloWorld123Python

Explanation

  • list comprehension [char for char in s1 if char.isalnum()] iterates through each character in the string s and includes only those that are alphanumeric (letters and numbers) using the isalnum() method.
  • ''.join() method combines the filtered characters into a single string, which is then stored in s2 and printed, showing the cleaned result.

Using filter() with str.isalnum()

filter() function combined with str.isalnum() filters out non-alphanumeric characters from a string by keeping only those that are letters or numbers.

Python
# Input string
s1 = "Hello, World! 123 @Python$"

# Use filter to keep only alphanumeric characters
s2 = ''.join(filter(str.isalnum, s1))

# Print the cleaned string
print(s2)

Output
HelloWorld123Python

Explanation

  • filter(str.isalnum, s1) function applies the isalnum() method to each character in s , keeping only the alphanumeric characters (letters and numbers).
  • ''.join() method combines the filtered characters into a single string, which is stored in s2 and printed as the result.

Using a for Loop

Using a for loop, we can iterate through each character in a string and check if it is alphanumeric. If it is, we add it to a new string to create a cleaned version of the original.

Python
# Input string
s1 = "Hello, World! 123 @Python$"

# Initialize an empty string
s2 = ''

# Iterate through each character in the string
for char in s1:
    # Check if the character is alphanumeric
    if char.isalnum():
        s2 += char

# Print the cleaned string
print(s2)

Output
HelloWorld123Python

Explanation

  • The for loop iterates through each character in input_string and the if char.isalnum() condition checks if the character is alphanumeric (letters or numbers).
  • If the character is alphanumeric, it is appended to s2, resulting in a new string that contains only alphanumeric characters, which is then printed.


Next Article

Similar Reads

three90RightbarBannerImg