Categories
Python Answers

How to remove all special characters, punctuation and spaces from string with Python?

Spread the love

Sometimes, we want to remove all special characters, punctuation and spaces from string with Python.

In this article, we’ll look at how to remove all special characters, punctuation and spaces from string with Python.

How to remove all special characters, punctuation and spaces from string with Python?

To remove all special characters, punctuation and spaces from string with Python, we can call re.sub with a regex that matches all the charaters we’re looking for and replace them with empty strings.

For instance, we write

re.sub('[^A-Za-z0-9]+', '', my_string)

to call re.sub with a regex that matches all special characters, punctuation and spaces.

Then we use an empty string as the 2nd argument to replace all the matched characters in my_string with empty strings.

Conclusion

To remove all special characters, punctuation and spaces from string with Python, we can call re.sub with a regex that matches all the charaters we’re looking for and replace them with empty strings.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *