Remove Spaces From String In Python

In this post, I will show you the different techniques for how to remove spaces from string in python. So without further ado let’s get started.

1. Using replace() method

replace() is the method of string data type that is used to substitute a specified phrase with another specified phrase from the string.

In the following code example, we have used it to replace all space characters inside the string with an empty string character.

# program to remove spaces from string in python.
def remove_space(string):
    # Simply replace all spaces with empty string
    return string.replace(" ","")

s = "This Is Test 1  2  3" # String with spaces
r = remove_space(s) # remove spaces
print(r)

Output :

Save and run the above code you should see the following output.

output of remove spaces from string in python

2. Using join() and split()

In the following code snippet, we will use join() and split() methods to remove space from the string.

join() method takes an iterable as an argument and returns a string by joining all its elements, separated by a string separator.

the split() method divides the string into the list.

# python remove space from the string
def remove_space(string):
    # Split string by space and convert to list
    lis = string.split()

    # Use the join method to convert the list back to string
    string = ''.join(lis)
    return string

s = "This Is Test 1  2  3" # String with spaces
r = remove_space(s) # remove spaces
print(r)

3. Using For Loop

In this code example, we will use for loop to iterate through each character of the input string and add each character other than space to the new string and return that new string to the caller.

# use for loop to remove spaces from string in python
def remove_space(string):
    final = '' # initialize an empty string

    # Loop through input string
    for char in string:

        # Check if char is not space
        if char != ' ':
            final += char # Add char to string
    return final

s = "This Is Test 1  2  3" # String with spaces
r = remove_space(s) # remove spaces
print(r)

4. Using Regex

In this code example, we will use a regular expression to remove space characters from the string.

import re

# use regex to remove spaces from string in python
def remove_space(string):
    return re.sub(r"\s+", "", string)

s = "This Is Test 1  2  3" # String with spaces
r = remove_space(s) # remove spaces
print(r)

That’s a wrap for this tutorial of how to remove space from a string in python.

Also read about python program to multiply two matrices

Leave a Reply