Open In App

Remove All Characters Except Letters and Numbers – Python

Last Updated : 19 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we’ll learn how to clean a string by removing everything except letters (A–Z, a–z) and numbers (0–9). This means getting rid of:

  • Special characters (@, #, !, etc.)
  • Punctuation marks
  • Whitespace

For example, consider a string s = “[email protected], after removing everything except the numbers and alphabets the string will become “Geeksno1”.

Let’s explore different ways to achieve this in Python:

Using Regular Expressions (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.
  • The result is a clean string with only alphanumeric characters..

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 filter() with str.isalnum()

The filter() function applies a condition (in this case, isalnum) to each character and filters out the rest.

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 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)

Output
HelloWorld123Python

Explanation:

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

Also read: Strings, List comprehension, re.sub(), regular expressions, filter, str.isalnum(), ”.join() method.



Next Article

Similar Reads