VOOZH about

URL: https://www.geeksforgeeks.org/python/python-remove-all-characters-except-letters-and-numbers/

⇱ Remove All Characters Except Letters and Numbers - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove All Characters Except Letters and Numbers - Python

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.


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.


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.


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.


Output
HelloWorld123Python

Explanation:

  • The loop checks each character.
  • If it's alphanumeric, it's added to the result string s2.

Related Articles:

Comment