DEV Community

Ruchika Atwal
Ruchika Atwal

Posted on • Edited on

2 1

Remove extra space from text with regex - Python

Easy way to remove extra spaces from text, paragraph with regex in python

  • Import regular expression packages
import re
Enter fullscreen mode Exit fullscreen mode
  • Remove extra spaces from text.
text = "  Hi python   is a case   sensitive language.    "
text = re.sub(' +', ' ', text)
print("text : ", text)
Enter fullscreen mode Exit fullscreen mode

Explanation for above piece of code :

  1. re.sub() - is a function in used to replace sub-string with another sub-string.
  2. first argument in sub function is regular expression to find sub-string expression that will replace, i.e: ' +' (space with +) capture number of spaces.
  3. second argument is what will replace in place of first argument, i.e: ' ' (one single space to replace with number of spaces)
  4. third argument is your piece of text variable that you want to clean.

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more