Python Replace Multiple Spaces With One

You can use regular expressions to replace multiple spaces with a single space in a Python string. Here’s how you can do it:

Example : Python String Replace Multiple Spaces with Single Space Example

main.py

import re

# Declare String Variable
ytslogen = "Hello, This is Pakainfo.com. This is TechWebsite."

# Python replace multiple spaces with single space
finalresults = re.sub(' +', ' ', ytslogen)

print(finalresults)

Result:

Hello, This is Pakainfo.com. This is TechWebsite.

Example 2:

python

import re

original_string = "This is a string with multiple spaces."

# Replace multiple spaces with a single space
modified_string = re.sub(r'\s+', ' ', original_string)

print("Original string:", original_string)
print("Modified string:", modified_string)

In this code:

  • re.sub() is a function from the re module that performs a regular expression-based substitution.
  • r’\s+’ is a regular expression pattern that matches one or more whitespace characters (spaces, tabs, newlines, etc.).
  • ‘ ‘ is the replacement string, which is a single space.
  • The re.sub() function replaces all occurrences of one or more whitespace characters with a single space, effectively collapsing multiple spaces into one.

Leave a Comment