How To Remove Spaces from a String In Python

Introduction

This tutorial provides examples of various methods you can use to remove whitespace from a string in Python.

A Python String is immutable, so you can’t change its value. Any method that manipulates a string value returns a new string.

Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

The examples in this tutorial use the Python interactive console in the command line to demonstrate different methods that remove spaces. The examples use the following string:

s = '  Hello  World   From DigitalOcean \t\n\r\tHi There  '

The output is:

Output
Hello World From DigitalOcean Hi There

This string has different types of whitespace and newline characters, such as space ( ), tab (\t), newline (\n), and carriage return (\r).

Remove Leading and Trailing Spaces Using the strip() Method

The Python String strip() method removes leading and trailing characters from a string. The default character to remove is space.

Declare the string variable:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

Use the strip() method to remove the leading and trailing whitespace:

  1. s.strip()

The output is:

Output
'Hello World From DigitalOcean \t\n\r\tHi There'

If you want to remove only the leading spaces or trailing spaces, then you can use the lstrip() and rstrip() methods.

Remove All Spaces Using the replace() Method

You can use the replace() method to remove all the whitespace characters from the string, including from between words.

Declare the string variable:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

Use the replace() method to replace spaces with an empty string:

  1. s.replace(" ", "")

The output is:

Output
'HelloWorldFromDigitalOcean\t\n\r\tHiThere'

Remove Duplicate Spaces and Newline Characters Using the join() and split() Methods

You can remove all of the duplicate whitespace and newline characters by using the join() method with the split() method. In this example, the split() method breaks up the string into a list, using the default separator of any whitespace character. Then, the join() method joins the list back into one string with a single space (" ") between each word.

Declare the string variable:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

Use the join() and split() methods together to remove duplicate spaces and newline characters:

  1. " ".join(s.split())

The output is:

Output
'Hello World From DigitalOcean Hi There'

Remove All Spaces and Newline Characters Using the translate() Method

You can remove all of the whitespace and newline characters using the translate() method. The translate() method replaces specified characters with characters defined in a dictionary or mapping table. The following example uses a custom dictionary with the string.whitespace string constant, which contains all the whitespace characters. The custom dictionary {ord(c): None for c in string.whitespace} replaces all the characters in string.whitespace with None.

Import the string module so that you can use string.whitespace:

  1. import string

Declare the string variable:

  1. s = ' Hello World From DigitalOcean \t\n\r\tHi There '

Use the translate() method to remove all whitespace characters:

  1. s.translate({ord(c): None for c in string.whitespace})

The output is:

Output
'HelloWorldFromDigitalOceanHiThere'

Remove Whitespace Characters Using Regex

You can also use a regular expression to match whitespace characters and remove them using the re.sub() function.

This example uses the following file, regexspaces.py, to show some ways you can use regex to remove whitespace characters:

regexspaces.py
import re

s = '  Hello  World   From DigitalOcean \t\n\r\tHi There  '

print('Remove all spaces using regex:\n', re.sub(r"\s+", "", s), sep='')  # \s matches all white spaces
print('Remove leading spaces using regex:\n', re.sub(r"^\s+", "", s), sep='')  # ^ matches start
print('Remove trailing spaces using regex:\n', re.sub(r"\s+$", "", s), sep='')  # $ matches end
print('Remove leading and trailing spaces using regex:\n', re.sub(r"^\s+|\s+$", "", s), sep='')  # | for OR condition

Run the file from the command line:

python3 regexspaces.py

You get the following output:

Remove all spaces using regex:
HelloWorldFromDigitalOceanHiThere
Remove leading spaces using regex:
Hello  World   From DigitalOcean 	
	Hi There  
Remove trailing spaces using regex:
  Hello  World   From DigitalOcean 	
	Hi There
Remove leading and trailing spaces using regex:
Hello  World   From DigitalOcean 	
	Hi There

Conclusion

In this tutorial, you learned some of the methods you can use to remove whitespace characters from strings in Python. Continue your learning about Python strings.

Source:
https://www.digitalocean.com/community/tutorials/python-remove-spaces-from-string