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: 2021-09-20T10:23:57+05:30

929 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements