![]() |
VOOZH | about |
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.
re.sub() function replaces all characters that match a given pattern with a replacement. It’s perfect for pattern-based filtering.
HelloWorld123Python
Explanation:
"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.
HelloWorld123Python
Explanation:
List comprehension lets you filter characters efficiently in a single line.
HelloWorld123Python
Explanation:
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.
HelloWorld123Python
Explanation:
Related Articles: