Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Replace occurrences by K except first character
Next article icon

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
Python - Replace occurrences by K except first character
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python Regex-programs
  • Python string-programs
  • python-regex
Practice Tags :
  • python

Similar Reads

  • Get number of characters, words, spaces and lines in a file - Python
    Given a text file fname, the task is to count the total number of characters, words, spaces, and lines in the file. As we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to calculate the total number of characters, words, spaces, and line
    5 min read
  • Python Program To Remove all control characters
    In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is
    3 min read
  • Python - Remove N characters after K
    Given a String, remove N characters after K character. Input : test_str = 'ge@987eksfor@123geeks is best@212 for cs', N = 3, K = '@' Output : 'geeksforgeeks is best for cs' Explanation : All 3 required occurrences removed. Input : test_str = 'geeksfor@123geeks is best for cs', N = 3, K = '@' Output
    2 min read
  • Python - Replace occurrences by K except first character
    Given a String, the task is to write a Python program to replace occurrences by K of character at 1st index, except at 1st index. Examples: Input : test_str = 'geeksforgeeksforgeeks', K = '@' Output : geeksfor@eeksfor@eeks Explanation : All occurrences of g are converted to @ except 0th index. Input
    5 min read
  • Python - Remove characters till K element
    Sometimes, while working with Python, we can have problem in which we need to get all elements in list occurring after particular character in list. This kind of problem can have application in data domains and web development. Lets discuss certain ways in which this task can be performed. Method #1
    5 min read
  • Python - Remove all digits before given Number
    Given a String, remove all numeric digits before K number. Method #1 : Using split() + enumerate() + index() + list comprehension This is one of the ways in which this task can be performed. In this, we perform task of split() to get all words, getting index of K number using index() and list compre
    6 min read
  • Python | Extract characters except of K string
    Sometimes, while working with Python strings, we can have a problem in which we require to extract all the elements of string except those which present in a substring. This is quite common problem and has application in many domains including those of day-day and competitive programming. Lets discu
    6 min read
  • Python - Replace multiple characters at once
    Replacing multiple characters in a string is a common task in Python Below, we explore methods to replace multiple characters at once, ranked from the most efficient to the least. Using translate() with maketrans() translate() method combined with maketrans() is the most efficient way to replace mul
    2 min read
  • Python Program to Converts Characters To Uppercase Around Numbers
    Given a String, the following program converts the alphabetic character around any digit to its uppercase. Input : test_str = 'geeks4geeks is best1 f6or ge8eks' Output : geekS4Geeks is besT1 F6Or gE8Ek Explanation : S and G are uppercased as surrounded by 4.Input : test_str = 'geeks4geeks best1 f6or
    8 min read
  • Remove Multiple Characters from a String in Python
    Removing multiple characters from a string in Python can be achieved using various methods, such as str.replace(), regular expressions, or list comprehensions. Each method serves a specific use case, and the choice depends on your requirements. Let’s explore the different ways to achieve this in det
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences