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.
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)
The string is : python123:, .@! abc The expected string is : python123abc
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.