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:
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)
Watch a video course
Python - The Practical Guide
The above code will 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.