What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Remove Spaces from String in Python

  • Jan 06, 2022
  • 5 Minutes Read
Remove Spaces from String in Python

 

We can't change the value of a Python String because it's immutable. Any function that manipulates string values returns a new string, which must be explicitly assigned to the string otherwise the string value will remain unchanged. In this article, we'll learn how to remove spaces from a string in Python using several methods. So let's get started!

What are Strings in Python?

Strings are arrays of bytes in Python that represent Unicode characters. However, because Python lacks a character data type, a single character is merely a one-length string. One can use Square brackets can be used to access the string's elements.

How to create a string in Python?

Strings can be made by enclosing characters within single or double-quotes. In Python, triple quotes can be used to represent multiline strings and docstrings.

 For example:

# creating strings in Python
my_string = "Hello World"
print(my_string)    

# triple quotes string extending to multiple lines
my_string = """Hello, let's learn
                to code in Python"""
print(my_string)

 

Output:

Hello World
Hello,let's learn
        to code in Python

 

How to Remove Spaces from a String in Python?

There are 4 methods for removing whitespace from a string. But, in this section, we'll go through all of the Python-specific ways.

1) Using replace() method

All whitespaces are replaced with no space("") using the replace() method. 

For example:

def remove(string):
    return string.replace(" ", "")
    
string = ' a p p l e '
print(remove(string))

 

Output:

apple

 

2) Using split() and join()

First, using sep as the delimiter string, we utilize the split() function to return a list of the words in the string. The iterable is then concatenated using join().

For example:

def remove(string):
    return "".join(string.split())
      

string = ' a p p l e ' 
print(remove(string))

Output:

apple

 

3) Using python regex

For example:

import re
  
def remove(string):
    pattern = re.compile(r'\s+')
    return re.sub(pattern, '', string)
      

string = ' a p p l e '
print(remove(string))

 

Output:

apple

 

4) Using translate()

For example:

import string
  
def remove(string):
    return string.translate(None, ' \n\t\r')
      

string = ' a p p l e '
print(remove(string))

 

Output:

apple

 

Remove Spaces from the Beginning of a String in Python

The following method will only remove spaces from the beginning of the string in python.

For  example:

my_string = "    Rose"
print(my_string.lstrip())

 

Output:

Rose

 

Remove Trailing Spaces from a String in Python

Using this method, only the trailing spaces can be removed in a string.

For example:

my_string = "    Rose   "
print(my_string.rstrip())
     

 

Output:

      Rose

 

The string strip() method can be used to eliminate spaces from both the beginning and end of a string.  Learn more about rstrip in python here.

For example:

my_string = "    Rose  "
print(my_string.strip())

print(len(my_string.strip()))

 

Output: 

Rose
5

 

Because spaces at the beginning and end of the string have been eliminated, the strip() method returns a string with just 5 characters.

Conclusion

In summary, we learnt different methods to remove spaces within a string and also methods to remove spaces from the beginning and end of a string. You now have a sufficient number of options for replacing or removing white spaces from Python strings. Simply choose the one that appeals to you and is appropriate for the situation at hand.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Adrita Das
I am Adrita Das, a Biomedical Engineering student and technical content writer with a background in Computer Science. I am pursuing this goal through a career in life science research, augmented with computational techniques. I am passionate about technology and it gives immense happiness to share my knowledge through the content I make.