How to Remove Non-Alphanumeric Characters from a Python String?

Estimated read time 1 min read

To remove non-alphanumeric characters from a Python string, you can use regular expressions and the re module. Here is an example code snippet that removes non-alphanumeric characters from a string:

import re

original_string = "Hello, World! This is a #Python string."

# Remove non-alphanumeric characters
clean_string = re.sub(r'\W+', '', original_string)

print(clean_string)  # Output: "HelloWorldThisisaPythonstring"

In this code, we import the re module to use regular expressions.

Next, we define an original string (original_string) that contains non-alphanumeric characters.

Then, we use the re.sub() function to substitute all non-alphanumeric characters with an empty string. The \W in the regular expression pattern matches any non-word character (i.e., any character that is not alphanumeric or an underscore), and the + matches one or more occurrences of the pattern.

Finally, we print the cleaned string (clean_string) that does not contain non-alphanumeric characters.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply