A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-remove-all-characters-except-letters-and-numbers/ below:

Remove All Characters Except Letters and Numbers - Python

Remove All Characters Except Letters and Numbers - Python

Last Updated : 11 Jul, 2025

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:

For example, consider a string s = "Geeks@no.1", 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:

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:

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:

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:

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



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4