Tutorial

Effective Ways to Remove Spaces from Strings in Python

Updated on December 18, 2024
Effective Ways to Remove Spaces from Strings in Python

Introduction

In this tutorial, you will learn various methods to remove whitespace from a string in Python. Whitespace characters include spaces, tabs, newlines, and carriage returns, which can often be unwanted in strings when processing text data.

Python strings are immutable, meaning their values cannot be changed after they are created. Therefore, any method that manipulates a string will return a new string with the desired modifications. This tutorial will cover different techniques, including built-in string methods and regular expressions, to effectively remove whitespace from your strings.

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 various methods to remove whitespace characters from strings in Python. These methods include using the strip(), replace(), join() and split(), translate(), and regular expressions. Each method has its own use case and can be chosen based on the specific requirements of your task.

To further enhance your understanding of string manipulation in Python, you can refer the following tutorials:

By using these resources, you can deepen your knowledge and become more proficient in handling strings in Python.

FAQs

How do you remove spaces from a string in Python?

There are several ways, depending on which spaces you want to remove:

  • To remove all spaces: Use replace():
my_string = "Hello World"
no_spaces = my_string.replace(" ", "")
# no_spaces is now "HelloWorld"
  • To remove leading and trailing spaces only: Use strip():
my_string = "  Hello World  "
trimmed = my_string.strip()
# trimmed is now "Hello World"
  • To remove spaces using a regular expression (to handle multiple whitespace types):
import re
my_string = "Hello   World"
no_spaces = re.sub(r"\s+", "", my_string)
# no_spaces is now "HelloWorld"

How to remove spaces in string?

To remove all spaces, use my_string.replace(" ", ""). To remove only leading and trailing spaces, use my_string.strip().

What does strip() do in Python?

The strip() method returns a new string by removing all leading (at the start) and trailing (at the end) whitespace characters. For example:

my_string = "   Hello World   "
trimmed = my_string.strip()  
# trimmed = "Hello World"

How do you remove spaces trim in Python string?

To “trim” spaces—meaning to remove them only from the start and end of the string—use the strip() method:

my_string = "   Trim me   "
trimmed = my_string.strip()  
# trimmed = "Trim me"

What is stripping whitespace in Python?

“Stripping whitespace” refers to removing any leading and trailing whitespace characters (including spaces, tabs, and newlines) from a string. The strip(), lstrip(), and rstrip() methods are commonly used for this purpose.

How do I remove part of a string in Python?

To remove a known substring from a string, you can use replace():

my_string = "Hello World"
removed_part = my_string.replace("World", "")
# removed_part = "Hello "

If you need to remove content by index, you can use slicing:

my_string = "Hello World"
# Remove "lo Wo"
removed_part = my_string[:3] + my_string[8:]
# removed_part = "Hello d"

Which method is used to remove whitespace?

The strip() method is used to remove whitespace from the start and end of a string. For removing whitespace from the entire string, replace() can be used, and for more sophisticated patterns, you can use regular expressions via the re module.

How to remove space in Python print?

When using print() with multiple arguments, Python adds a space by default. To avoid this, you can specify the sep parameter:

print("Hello", "World", sep="")
# Outputs: "HelloWorld"

If your string already contains spaces you want to remove, apply .replace(" ", "") or strip() before printing:

my_string = "Hello World"
print(my_string.replace(" ", ""))
# Outputs: "HelloWorld"

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author


Default avatar

Sr Technical Writer

Senior Technical Writer @ DigitalOcean | 2x Medium Top Writers | 2 Million+ monthly views & 34K Subscribers | Ex Cloud Consultant @ AMEX | Ex SRE(DevOps) @ NUTANIX


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 2, 2021

Thank you so much.

- Sai Vinay Palakodeti

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 30, 2020

    hey nice one thank you helped me in my code

    - Moulya

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 1, 2020

      Very helpful article, Pankaj. Thank you for this

      - ypll

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 16, 2020

        greeting= “Hello” user= “Guy” message= “welcome to the thunderdome Friend” print(greeting.upper(), user.capitalize(), message.strip( ).lower() ) ive also tried print(greeting.upper(), user.capitalize(), message.replace(" ", " ").lower() ) goal is to lowercase friend and get rid of white space. when I run the .py file through cmd it just returns HELLO Guy welcome to the thunderdome friend no matter what I seem to try

        - Pegel

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 11, 2020

          the replace function helped me where i was thinking of a more complex solution. So thank you

          - Munir

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 26, 2020

            This was so helpful! Thanks for putting this together! :)

            - Azmain Nisak

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 18, 2019

              let me explain you with an simple example s= (" PYTHON “) #so here i am using both and leading and trailing spaces output= s.strip(” “) # in between double quotes i am using space as i have used space before and after PYTHON print(output) # you will get output as “PYTHON” … another example while using idle --------------------------------------- >>> s= (” python ") >>> s.strip() ‘python’ >>> see both the trailing and leading spaces have been removed

              - DEEPAK

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                December 16, 2018

                You really need to point out that the functions create and return a new string, they do not change the original. Yes, strings being immutable is a foundational Python concept but someone who’s looking for this level of help is probably very new to Python. It can be incredibly frustrating for a beginner to find a page like this and do: s = " My string with leading/trailing spaces ’ s.strip() print(s) What the heck? It doesn’t work!

                - DJ

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  October 22, 2018

                  I don’t see anymore the date things were published. Why is it removed? Regards

                  - Valentino

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Become a contributor for community

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    DigitalOcean Documentation

                    Full documentation for every DigitalOcean product.

                    Resources for startups and SMBs

                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                    Get our newsletter

                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                    New accounts only. By submitting your email you agree to our Privacy Policy

                    The developer cloud

                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Get started for free

                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                    *This promotional offer applies to new accounts only.