Python String – Remove spaces

Python String – Remove spaces

To remove spaces from a string in Python, you can use re (regular expression) library. Use re.sub() function, and replace all whitespace characters with an empty string in the given string.

In this tutorial, we shall go through examples where we shall take a sample string, and remove all the white spaces from the string.

1. Remove spaces from string using re sub() function in Python

Consider that we are given a string in x, and we have to remove all the spaces (all possible white space characters) from this string x.

Steps

  1. Import re library.
import re
  1. Given a string in x.
x = "This is a sample text."
  1. Call re.sub() function, and pass the regular expression for white spaces r'\s' for the first argument, empty string for the second argument, and given string for the third argument.

The first argument is the pattern (search) string, the second argument is the replacement string, and the third argument is the source string. re.sub() function replaces all the occurrences of given pattern in the source string with replacement string.

re.sub(r'\s', '', x)
  1. The re.sub() method returns a new string with all the white spaces replaced with empty string, effectively removing all the spaces from the string. You may store the returned value in a variable, say x_without_spaces, and use it for your requirement.
x_without_spaces = re.sub(r'\s', '', x)

Program

The complete program to remove all the spaces from the string using re.sub() function.

Python Program

import re

# Given string
x = "This is a sample text."

# Remove all spaces from string
x_without_spaces = re.sub(r'\s', '', x)

print(f"Given string\n\"{x}\"\n")
print(f"Result string\n\"{x_without_spaces}\"")
Run Code Copy

Output

Given string
"This is a sample text."

Result string
"Thisisasampletext."

Summary

In this tutorial, we learned how to remove spaces from a string using re.sub() function, with an example program explained with steps in detail.

Related Tutorials

Code copied to clipboard successfully 👍