W3docs

Remove all special characters, punctuation and spaces from string

Here is an example of code that removes all special characters, punctuation, and spaces from a string in Python:

Here is an example of code that removes all special characters, punctuation, and spaces from a string in Python:

remove all special characters, punctuation, and spaces from a string in Python

import re

def remove_special_characters(string):
    return re.sub(r"[^a-zA-Z0-9]+", "", string)

example_string = "Hello, World! How are you today?"
cleaned_string = remove_special_characters(example_string)
print(cleaned_string)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

The above code will output:

output

HelloWorldHowareyoutoday

The function remove_special_characters uses the re.sub() method, which performs a search-and-replace on the input string. The regular expression [^a-zA-Z0-9]+ matches one or more characters that are not letters or numbers, and replaces them with an empty string. The ^ symbol in the regular expression means that everything that doesn't match the pattern inside the square brackets will be returned, which is the desired outcome in this case.