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.

Updated on: 20-Sep-2021

664 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements