Remove All Characters Except Letters and Numbers Python (original) (raw)
Last Updated : 29 Oct, 2025
Given a string that contains letters, numbers, and special characters, the task is to remove everything except letters (A–Z, a–z) and numbers (0–9). For example:
**Input: "Geeks@no.1"
**Output: "Geeksno1"
Below are some of the most efficient methods to achieve this in Python.
Using re.sub()
re.sub() function replaces all characters that match a given pattern with a replacement. It’s perfect for pattern-based filtering.
Python `
import re s1 = "Hello, World! 123 @Python$" s2 = re.sub(r'[^a-zA-Z0-9]', '', s1) print(s2)
`
Output
HelloWorld123Python
**Explanation:
- **[^a-zA-Z0-9] matches any character that is not a letter or number.
- **re.sub() replaces these characters with an empty string.
Using filter() with str.isalnum()
"filter()" function applies a given condition to each element in an iterable and keeps only those that return True, "str.isalnum()" method checks whether a character is alphanumeric (letters or digits). They can be implemented together to filter out all non-alphanumeric characters.
Python `
s1 = "Hello, World! 123 @Python$" s2 = ''.join(filter(str.isalnum, s1)) print(s2)
`
Output
HelloWorld123Python
**Explanation:
- **filter(str.isalnum, s1) keeps only characters where **isalnum() is **True.
- ****''.join()** combines the valid characters into a new string.
Using List Comprehension with str.isalnum()
List comprehension lets you filter characters efficiently in a single line.
Python `
s1 = "Hello, World! 123 @Python$" s2 = ''.join([char for char in s1 if char.isalnum()]) print(s2)
`
Output
HelloWorld123Python
**Explanation:
- **char.isalnum() returns **True for letters and numbers.
- Only those characters are included and joined into a new string.
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 `
s1 = "Hello, World! 123 @Python$" s2 = '' for char in s1: if char.isalnum(): s2 += char
print(s2)
`