| by Arround The Web | No comments

Python Remove Spaces from String

Removing Spaces” from a string is one of the common tasks in text processing. The term “Spaces” refers to empty spaces that can appear at the beginning, end, or within the characters of a string. Sometimes, we may want to remove all spaces or a few of them, depending on the situation. This blog post will explore different ways to remove spaces from a string in Python using various built-in and other methods.

How to Remove/Eliminate Spaces From Python String?

The following methods are utilized to eliminate spaces from the Python string:

Method 1: Remove Spaces From String in Python Utilizing the “replace()” Method

The “replace()” method replaces the instances of a substring with different substrings within a string. It retrieves a unique string with the replaced substring(s).

Syntax

new_string = original_string.replace(old_substring, new_substring, count)

In the above syntax:

  • The “original_string” parameter is the string in which the substring(s) are to be replaced/changed.
  • The “old_substring” parameter is the substring to be replaced.
  • The “new_substring” refers to the substring that will replace/modify the old substring.
  • The “count” (optional) parameter corresponds to the maximum number of times the “old substring” should be replaced. If not provided, all instances of the old substring will be modified/replaced.

Example

The following code is used to remove the spaces from the string:

string_value ="Hello and Welcome to Python Guide."
output=string_value.replace(" ", "")
print(output)

In the above code, the “replace()” method takes the blank space as a first argument and takes an empty(without any space) value as a second argument to remove all the spaces from the entire string.

Output

The above snippet verified that all the spaces have been removed from the entire string.

Method 2: Remove Spaces From String in Python Utilizing the “translate()” Method

The “translate()” method translates the characters in a string. This method can also be utilized to remove/delete the spaces from a string in Python.

Syntax

str.translate(table)

This method takes a translation “table” as an argument, which is a dictionary or a mapping of Unicode ordinals to translations, and returns a new string with the translated characters.

Example

The below code shows us how to remove spaces from a string using the “translate()” method:

import string
string_value ="Hello and Welcome to Python Guide."
output = string_value.translate({ord(c): None for c in string.whitespace})
print(output)

According to the above code:

  • The “string” module is imported and the string is created.
  • The “translate()” method of the string object removes all the whitespace characters (such as spaces, tabs, and newlines) from the given string value.
  • It does this by creating a dictionary that maps each whitespace character to “None” and passing it as an argument to translate.

Output

The above output snippet implies that all the spaces have been removed.

Method 3: Remove Spaces From String in Python Using Regex Expression

A “regex expression” is a sequence of characters that defines a pattern used to match a set of strings. It can be used to search and manipulate text in a string. Regular expressions are defined using special characters.

Example

Here is a sample code:

import re
string_value ="Hello and Welcome to Python Guide."
output = re.sub("\\s+", "", string_value)
print(output)

In the above example code, the “re.sub()” method takes the regex pattern that specifies the spaces as its first argument and the empty string(having no spaces) as a second argument to remove all the spaces from the string.

Output

Method 4: Remove Spaces From String in Python Utilizing the “strip()” Method

The “strip()” method is employed to remove/eliminate whitespace characters from the start and end of a string.

Syntax

str.strip([chars])

This method takes an optional argument “chars” that specifies which characters to remove.

Example 1: Remove Leading and Trailing Spaces

Let’s overview the below example code:

string_value =" Hello and Welcome to Python Guide. "
print('With Leading and Trailing Spaces: ', string_value)
output = string_value.strip()
print('\nWithout Leading and Trailing Spaces:', output)

In this code block, the “strip()” method removes all the leading and trailing spaces from the defined string.

Output

In this outcome, the spaces at the start and at the end have been removed successfully.

Example 2: Remove Leading Spaces

The below-stated code is used to remove leading spaces:

string_value =" Hello and Welcome to Python Guide. "
print('With Leading Spaces:', string_value)
output = string_value.lstrip()
print('\nWithout Leading Spaces:', output)

In this code snippet, the “lstrip()” method is used to remove only the leading spaces from the initialized string.

Output

The leading spaces have been removed based on the above output.

Example 3: Remove Trailing Spaces

Here, the “trailing” spaces will remove using the below code:

string_value =" Hello and Welcome to Python Guide. "
print('With Trailing Spaces:', string_value)
output = string_value.rstrip()
print('\nWithout Trailing Spaces:', output)

This code uses the “rstrip()” method to remove only the trailing spaces from the initialized string.

Output

As seen, the trailing spaces have been removed accordingly.

Method 5: Remove Spaces From String in Python Using the “reduce()” Function and “Conditional” Statement

The “reduce()” function is utilized to reduce an iterable to a single value by applying a specified function. A conditional statement can be used inside the function to apply the reduction conditionally. Both of these methods are used in combination to remove spaces from the given string.

Syntax

functools.reduce(function, iterable)

The function accepts two parameters, the first is a “function” that takes two arguments and retrieves a single value, and the second is “iterable”.

Example

Let’s overview the below example code:

from functools import reduce
string_value ="Hello and Welcome to Python Guide."
output = reduce(lambda x, y: (x+y) if (y != " ") else x, string_value, "")
print(output)

In the above code lines:

  • The “reduce()” function takes the “lambda” function as a first argument, the given string as the second argument, and the empty string as a third argument, respectively.
  • The lambda expression returns the concatenation of two strings if the second string is not a space, otherwise, it returns the first string.

Output

Method 6: Remove Spaces From String in Python Utilizing “isspace()” Method

The “isspace()” method is utilized to check if a string only consists of whitespace characters. It yields “True” if the string is all whitespace, and “False” otherwise. This method can be utilized along with the “for” loop to remove the spaces in the initialized string.

Syntax

str.isspace()

Example

The following code is an example:

string_value ="Hello and Welcome to Python Guide."
new_string=""
for i in string_value:
    if(not i.isspace()):
        new_string+=i
print(new_string)

According to this code:

  • The “for” loop iterates over each character in the string and uses an “if” statement to check if the current character is a space or not.
  • The “isspace()” method retrieves “True” if the character is a space and “False” otherwise.
  • The “not” operator negates the result, so we only enter the “if” block if the character is not a space.
  • The “+=” operator appends the current character to the empty string at the end.

Output

The above output displays that the string spaces have been removed.

Method 7: Remove Spaces From String in Python Using “itertools.filterfalse()”

The “itertools.filterfalse()” function is used to filter an iterable based on a condition. This function can also be implemented to extract string spaces in Python.

Syntax

itertools.filterfalse(function, iterable)

This function accepts two parameters/arguments, a “function” that returns a boolean value and an “iterable”. The function produces an iterator comprising only those elements from the iterable that fail to meet the specified condition.

Example

This code is used to remove string spaces via the “itertools.filterfalse()” method:

import itertools
string_value ="Hello and Welcome to Python Guide."
resList = list(itertools.filterfalse(lambda x: x == ' ', string_value))
new_str = ''.join(resList)
print(new_str)

In the above code:

  • The “itertools” module is imported and the string value is defined, respectively.
  • The “filterfalse()” function from the “itertools” module creates a list called “resList” that contains all the characters from “string_value” except for spaces.
  • The “lambda” function passed to the “filterfalse()” function checks whether each character is equal to a space character (‘ ‘). If it is not equal, the character is included in the output.
  • Lastly, the “join()” method is used to join all the characters in “resList” into a single string variable called “new_str“.

Output

Method 8: Remove Spaces From String in Python Using “for” Loop and “join()” Method

The “join()” method is used to join a list of strings into a single string, with a specified delimiter between each string. This method is used along with the “for” loop to remove the string spaces.

Syntax

delimiter.join(iterable)

Example

The below example code is used to remove spaces from a string using the “for” loop and “join()” method:

string_value ="Hello and Welcome to Python Guide."
new_str = ""
for i in string_value:
    if i != " ":
        new_str += i
print("".join(new_str))

In this code block, the “for” loop iterates over the string, and by using the “!=” operator, it checks whether there are spaces in the string or not. In the case of no space occurrences, it joins them to a new string named “new_str”.

Output

Based on the above snippet, it can be observed that all the spaces from the string have been removed successfully.

Conclusion

To remove spaces from the string, various methods such as “replace()”, “translate()”, “Regex Expression”, “strip()”, “reduce()” function with a conditional statement, “isspace()” method, “itertools.filterfalse()” function, or “for” loop with “join()” methods are used in Python. These methods efficiently eliminate the spaces from the string. This Python blog post demonstrated these methods using relevant examples.

Share Button

Source: linuxhint.com

Leave a Reply