You are currently viewing Python Remove Spaces From String

How to remove spaces from a string in Python? Removing spaces from a string involves eliminating any whitespace characters present within the string. Whitespace characters include spaces, tabs, and newline characters. The process consists of scanning the entire string and then excluding or replacing these whitespace characters with no characters (i.e., removing them).

Advertisements

You can remove spaces from a string in Python using many ways, for example, by using replace(), split() & join(), translate(), regex, reduce(), regex.findall(), map() & lambda(), for loop & join(), itertools.filterfalse(), and isspace() functions. In this article, I will explain how to remove spaces from a string by using all these functions with examples.

Related: In Python, you can also remove punctuations from a string.

1. Quick Examples of Remove Spaces From String

If you are in a hurry, below are some quick examples of removing spaces from a string.


# Quick examples of removing spaces from string

# Initialize the string
string = " Welcome To Sparkbyexamples "

# Example 1: Using replace() method
# Remove spaces from a string 
def remove(string):
    return string.replace(" ", "")
result = remove(string)

# Example 2: Using split() and join() methods
# Remove spaces from a string 
def remove(string):
    return "".join(string.split())
result = remove(string)

# Example 3: Using translate() method
# Remove spaces from a string 
def remove(string):
    translation_table = str.maketrans("", "", " ")
    return string.translate(translation_table)    
result = remove(string)

# Example 4: Using regex
# Remove spaces from a string 
def remove(string):
    return re.sub(r'\s+', '', string)   
result = remove(string)

# Example 5: Using reduce() function 
# To remove spaces from a string
def remove_spaces(string):
    return reduce(lambda x, y: (x+y) if (y != " ") else x, string, "");
result = remove_spaces(string)

# Example 6: Using regex.findall() method 
# To remove spaces from a string
def remove_spaces(string):
    return  ''.join(re.findall(r'[a-zA-Z]+', string))
result = remove_spaces(string)

# Example 7: Using map() and lambda() function 
# To remove spaces from a string
result = ''.join(list(map(lambda x: x.strip(), string.split())))

# Example 8: Using for loop and join() function 
new_string = ""
for char in string:
    if char != " ":
        new_string += char
result = "".join(new_string)

# Example 9: Using itertools.filterfalse() method 
# To remove spaces from a string
def remove_spacee(string):
    resList = list(itertools.filterfalse(lambda x: x == ' ', string))
    return ''.join(resList)
result = remove_spacee(string)

# Example 10: Using isspace() method 
# To remove spaces from a string
def remove(string):
    result=""
    for i in string:
        if(not i.isspace()):
            result+=i
    return result
result = remove(string)

2. Remove Spaces from a String Using replace() Method

You can remove spaces from a string using the replace() method. For example, first, the string is initialized with the value "Welcome To Sparkbyexamples". The function remove is defined, which takes a string as input and returns the same string with spaces removed.

The replace() method is used within the remove function to replace all occurrences of spaces with an empty string, effectively removing them. The remove function is then called with the original string, and the result is stored in the variable result. Finally, the original string and the result after removing spaces are printed.


# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:",string)

# Using replace() method
# Remove spaces from a string 
def remove(string):
    return string.replace(" ", "")
result = remove(string)
print("After removing spaces from a string:",result)

Yields below output.

python remove spaces string

The spaces at the beginning and end of the original string have been successfully removed, as well as any other spaces within the string.

3. Remove Spaces from a String Using split() and join() Methods

Alternatively, you can use the split() and join() methods to remove spaces from a string. For example, first, the string is initialized with the value "Welcome To Sparkbyexamples" (note the spaces at the beginning and ending). The function remove is defined, which takes a string as input. Within the remove function, the split() method is used on the input string. This method splits the string into a list of substrings based on whitespace characters(spaces, tabs, newlines, etc.). If you don’t provide any argument to split(), it will split the string on all whitespace characters.

Then, the join() method is used to join the substrings obtained from the split() back into a single string. The join() method concatenates the elements of an iterable (in this case, the list of substrings obtained from split()) into a single string, with an empty string "" as the separator between elements. The result after removing spaces is returned from the remove function.

Related: You can also remove commas from a Python string.


# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:",string)

# Using split() and join() methods
# Remove spaces from a string 
def remove(string):
    return "".join(string.split())
result = remove(string)
print("After removing spaces from a string:",result)

Yields the same output as above.

4. Remove Spaces from a String Using translate() Method

To remove spaces from a string use the translate() method. To create a translation table use str.maketrans() where you map the space character to None. Then, you can use the translation table with the translate() method to remove spaces.

The str.maketrans("", "", " ") function creates a translation table where spaces are mapped to None, effectively removing them. Then, the translate() method is used with this translation table to remove the spaces from the original string.


import string
 
# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:",string)

# Using translate() method
# Remove spaces from a string 
def remove(string):
    translation_table = str.maketrans("", "", " ")
    return string.translate(translation_table)    
result = remove(string)
print("After removing spaces from a string:",result)

Yields the same output as above.

5. Remove Spaces from a String Using Regex

You can remove spaces from a string using regular expressions (regex) in Python. You can use the re.sub() function from the re module to replace all occurrences of spaces with an empty string.

In the below example, \s+, this regex pattern matches one or more whitespace characters (spaces, tabs, newlines, etc.). The re.sub() function searches for the regex pattern \s+ in the input string string and replaces all occurrences of it with an empty string '', effectively removing all spaces from the string.


import re
 
# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:",string)

# Using regex
# Remove spaces from a string 
def remove(string):
    return re.sub(r'\s+', '', string)   
result = remove(string)
print("After removing spaces from a string:",result)

Yields the same output as above.

6. Remove Spaces from a String Using reduce() Function

You can also use the reduce() function with a lambda function to remove spaces from a string. The reduce() function takes three arguments, the lambda function, the iterable (the input string string), and an initial value "". The lambda function (lambda x, y: (x + y) if (y != " ") else x) takes two arguments x and y. It checks if the character y is not a space. If y is not a space, it concatenates x and y (i.e., removes the space by not adding it to x). If y is a space, it returns x unchanged (i.e., keeps the space in the string).

The reduce() function iterates through each character of the string string. The lambda function is applied to each character in sequence, starting with the initial value "". The result is accumulated by concatenating non-space characters and preserving spaces. The final result, after removing spaces from the string, is returned.


from functools import reduce
 
# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:",string)

# Using reduce() function 
# To remove spaces from a string
def remove_spaces(string):
    return reduce(lambda x, y: (x+y) if (y != " ") else x, string, "");
result = remove_spaces(string)
print("After removing spaces from a string:", result)

Yields the same output as above.

7. Remove Spaces from a String Using regex.findall() Method

You can also use re.findall() method to remove spaces from the string and only retain alphabetic characters. It uses the regex pattern [a-zA-Z]+ to find all sequences of one or more alphabetic characters in the input string and then joins these sequences together to form the new string without spaces.

In the below example, the re.findall(r'[a-zA-Z]+', string) uses the regex pattern [a-zA-Z]+ to find all sequences of one or more alphabetic characters (both lowercase and uppercase letters) in the input string string. The re.findall() function returns a list of all occurrences of such sequences in the input string. The "".join() method joins the elements of the list returned re.findall() into a single string without any separator (i.e., an empty string "" is used as the separator). This effectively concatenates all the alphabetic sequences together to form a new string without spaces.


import re
 
# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:",string)

# Using regex.findall() method 
# To remove spaces from a string
def remove_spaces(string):
    return  ''.join(re.findall(r'[a-zA-Z]+', string))
result = remove_spaces(string)
print("After removing spaces from a string:", result)

Yields the same output as above.

8. Using map() and lambda() Function

You can also use map() and lambda() functions to remove spaces from the string. string.split() is used to split the string into a list of substrings based on whitespace characters (spaces, tabs, newlines, etc.). Then, it applies lambda x: x.strip() using map() to remove spaces from each substring. Finally, it joins the modified substrings back together using ''.join() to form the new string without spaces.


# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:",string)

# Using map() and lambda() function 
# To remove spaces from a string
result = ''.join(list(map(lambda x: x.strip(), string.split())))
print("After removing spaces from a string:", result)

Yields the same output as above.

9. Using For Loop and join() Method

You can remove spaces from a string using the for loop and join() method. For example, you can initialize an empty string new_string to store the modified string without spaces. The for loop iterates through each character (char) in the input string string. Inside the loop, you check if the character char is not equal to a space " ". If it’s not a space, we concatenate the character to the new_string.

The loop continues until all characters in the input string have been processed. After the loop, new_string contains the modified string without spaces. You directly assign new_string to the result variable since new_string is already a string without spaces.


# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:",string)

# Using for loop and join() function 
new_string = ""
for char in string:
    if char != " ":
        new_string += char
result = "".join(new_string)
print("After removing spaces from a string:", result)

Yields the same output as above.

10. Using itertools.filterfalse() Method

You can use itertools.filterfalse() method to remove spaces from the string. For example, itertools.filterfalse(lambda x: x == ' ', string) filters out space characters from the input string string using the lambda function lambda x: x == ' '. The lambda function checks if a character x is equal to a space. The filterfalse() function returns an iterator containing the non-space characters from the input string.

list(itertools.filterfalse(lambda x: x == ' ', string)) converts the iterator to a list, which contains the non-space characters. The ''.join(resList) joins the non-space characters obtained from the list into a single string without any separator (i.e., an empty string "" is used as the separator). This effectively concatenates the non-space characters together to form a new string without spaces.


import itertools

# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:", string)

# Using itertools.filterfalse() method 
# To remove spaces from a string
def remove_spacee(string):
    resList = list(itertools.filterfalse(lambda x: x == ' ', string))
    return ''.join(resList)
result = remove_spacee(string)
print("After removing spaces from a string:", result)

Yields the same output as above.

11. Using isspace() Method

You can also use the isspace() method to remove spaces from the string. For example, the for loop iterates through each character (i) in the input string string. Inside the loop, if not i.isspace(): is used to check if the character i is not a space. If it’s not a space (i.e., a non-space character), it appends the character to the result string. The loop continues until all characters in the input string have been processed. After the loop, the result string contains the modified string without spaces.


# Initialize the string
string = " Welcome To Sparkbyexamples "
print("Original string:", string)

# Using isspace() method 
# To remove spaces from a string
def remove(string):
    result=""
    for i in string:
        if(not i.isspace()):
            result+=i
    return result
result = remove(string)
print("After removing spaces from a string:", resul

Yields the same output as above.

Conclusion

In this article, I have explained how to remove spaces from a string in Python by using replace(), split() & join(), translate(), regex, reduce(), regex.findall(), map() & lambda(), for loop & join(), itertools.filterfalse(), and isspace() functions with examples.

Happy Learning !!