Skip to content

Remove all spaces from string Python | Example code

  • by

There are many ways to remove space in Python. Some methods to remove all spaces from string Python are:-

  • replace()
  • split() and join()
  • regex (Regular expression )
  • translate()

Note: Python String strip() function will remove only leading and trailing whitespace, not between wrods.

Remove all spaces from string Python Example

Simple example code.

Using replace() method

This function will remove whitespaces between words too.

test_str = "Python code to remove whitespace"

print(test_str.replace(" ", ""))

Output:

Remove all spaces from string Python

Using split() and join() method

test_str = "Python code to remove whitespace"

print("".join(test_str.split()))

Regular expression

For this example, you have to import the “re” module. Try a regex with re.sub. You can search for all whitespace and replace it.

import re

test_str = "Python code to remove whitespace"
pattern = re.compile(r'\s+')

print(re.sub(pattern, '', test_str))

Using translate() method

Get rid of all the whitespaces using the string translate() function.

import string

test_str = "Python code to remove whitespace"

print(test_str.translate(test_str.maketrans('', '', ' \n\t\r')))

How to strip all whitespace from a string?

For example, want a string like “strip my spaces” to be turned into “stripmyspaces”, but I cannot seem to accomplish that with a strip():

Use replace method If you just want to remove spaces instead of all whitespace:

test_str = "strip my spaces"

print(test_str.replace(" ", ""))

Alternatively, use a regular expression:

import re

test_str = "strip my spaces"

print(re.sub(r"\s", "", test_str))

Output: stripmyspaces

Do comment if you have doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading