- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Remove all characters except letters and numbers
When it is required to remove all characters except for letters and numbers, regular expressions are used. A regular expression is defined, and the string is subjected to follow this expression.
Example
Below is a demonstration of the same
import re my_string = "python123:, .@! abc" print ("The string is : ") print(my_string) result = re.sub('[\W_]+', '', my_string) print ("The expected string is :") print(result)
Output
The string is : python123:, .@! abc The expected string is : python123abc
Explanation
The required packages are imported.
A string is defined and is displayed on the console.
A regular expression is defined, and the string is subjected to it.
The result is assigned to a variable.
This is displayed as output on the console.
Advertisements