How To Replace Multiple Spaces With A Single Space In Python

How To Replace Multiple Spaces With A Single Space In Python

To replace multiple spaces with a single space in Python, you can use RegEx or use join() and split() function. Follow the article to better understand.

Replace Multiple Spaces With A Single Space In Python

Use RegEx

In Python, Regular Expression is expressed via the ‘re’ module, so you have to import module ‘re’ before you want to use Regular Expression. Module ‘re’ has many methods and functions to work with RegEx, but one of the essential methods is ‘re.sub’.

The Re.sub() method will replace all pattern matches in the string with something else passed in and return the modified string.

Syntax:

re.sub(pattern, replace, string, count)

Parameters:

  • pattern: is RegEx.
  • replace: is the replacement for the resulting string that matches the pattern.
  • string: is the string to match.
  • count: is the number of replacements. Python will treat this value as 0, match and replace all qualified strings if left blank.

Example:

  • Import module ‘re’.
  • Call the re.sub() function to replace multiple spaces with a single space. Pattern initialization has the effect of replacing multiple spaces with a single space.
import re

multSpacesStr = "visit  learnshareit    website"

# Use the re.sub() function to replace multiple spaces with a single space
resultStr = re.sub('\\s+', ' ', multSpacesStr)
print(resultStr)

Output:

visit learnshareit website

Use join() and split() function

You can use the join() function combined with the split() function to replace multiple spaces with a single space.

Syntax:

str.join(object)

Parameters:

  • object: list or tuple containing elements that are strings to be concatenated.

The join() function returns an object that is a character string of the elements of the specified list or tuple joined together by a delimiter.

Syntax:

str.split(sep, maxsplit)

Parameters:

  • sep: the character that splits the original string into a small string. The default is a space.
  • maxsplit: maximum number of splits.

The split() function splits a string in Python with a delimiter and returns a list whose elements are just split strings.

Example:

  • Create a string with multiple spaces.
  • Use the join() function combined with the split() function to replace multiple spaces with a single space.
multSpacesStr = "visit   learnshareit    website         "

# Use the join() function combined with the split() function to replace multiple spaces
resultStr = " ".join(multSpacesStr.split())
print(resultStr)

Output:

visit learnshareit website

Summary

If you have any questions about how to replace multiple spaces with a single space in Python, leave a comment below. I will answer your questions. Thank you for reading!

Maybe you are interested:

Leave a Reply

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