Remove Punctuation in Python With Regex

Learn how to remove punctuation from a string in Python using regex, with practical examples and checks for text processing.

Before you start

This task runs locally in a Python environment. You need Python installed with the built-in re module, which does not require a separate service or package. Use a script or interactive Python session where you can inspect the resulting string.

Step-by-step instructions

Open a Python file or interactive shell and import the re module:

import re

Create a string to process, such as a short phrase with commas, periods, or other punctuation.

Use re.sub to replace punctuation with an empty string. One way is to match each punctuation character and remove it:

cleaned = re.sub(r'[^\w\s]', '', original_text)

This pattern keeps letters, numbers, underscores, and whitespace, and removes other characters such as commas, periods, exclamation marks, and question marks.

Print the result to confirm the punctuation is gone:

print(cleaned)

Check the output

Compare the original string with the cleaned string. Punctuation should be absent, while space-separated words should remain readable. If your string contains hyphens or apostrophes inside words, this pattern will also remove them unless the pattern is adjusted to keep those characters.

Whitespace and line breaks are retained because the pattern excludes only non-word, non-space characters.

Common problems and next steps

If the output removes letters or digits unexpectedly, check the regex for typos or an escaped backslash issue in the string literal. If you need to preserve certain punctuation, such as periods in decimals or apostrophes in contractions, add those characters to the allowed set or use a more specific pattern.

For Unicode text, a narrow ASCII punctuation list may miss characters such as dashes or quotation marks. In that case, use a Unicode-aware pattern with a punctuation property or an explicit list of the characters you want to remove.