In this article, you will learn how to remove whitespace characters from a string. Whitespace represents a character that users can use to specify white spacing.
This single character indicates an 'empty' representation. It signifies the tabs and spaces in the context of Python. Also, users can specify the exotic Unicode spaces with the whitespace.
These spaces separate and group elements of a string in a design, representing the relation of each element with the other. But strings are immutable, so when users want to change the value of strings, they will get a new Python string. Immutable data structures once get created, their values become permanent.
Methods to remove whitespaces from a string in Python
- strip() method
- replace() method
- split() and join() methods split() and join() methods
- sub() function or Regex
- reduce() function
- lstrip() method
- rstrip() method
- itertools.filterfalse() method
- isspace() method
- map() and lambda() function
- regex.findall() method
- Using NumPy
- loop and join() method
Method 1: Using the strip() method to remove leading and trailing whitespace from a string
The Python String strip() method is an inbuilt method. It returns a copy of the string after removing both leading and trailing characters. Users can pass desired string arguments based on how they want to remove the spaces.
Syntax:
string.strip([chars])
This method accepts only one parameter:
- chars: Users can use this parameter to specify the set of characters that get removed from the string. This parameter is optional. The method removes all leading and trailing whitespaces from the string if users do not pass any parameter by default.
Code Snippet:
a =" This is a Whitespace "
print(a.strip())
Output:
Explanation:
The above method will return a new string value where it has removed the leading and trailing whitespaces from the string.
Method 2: Using replace() method to remove all whitespaces from the string
The replace() method returns a copy of a string where it replaces the occurrences of a substring with another substring.
Syntax:
string.replace(old, new, count)
This method accepts three parameters:
- old: This parameter specifies the old substring users want to replace.
- new: Specifies the new substring which will replace the old one.
- count: This parameter counts the number of times users replace the old substring with the new one.
Code Snippet:
a = " This is a Whitespace "
print(a.replace(" ", ""))
Output:
Explanation:
Since this method accepts at least two arguments, we passed one double quotes whitespace and one blank space quote that indicates the method will remove all the whitespace characters from the string. It will return a new Python string with no spaces.
Method 3: Using split() and join() methods
Using the combination of both split() and join(), users can remove the whitespaces from the string. The split() method splits a string into a list of strings. After specifying the parameter by a separator, the method breaks the string.
Syntax of split():
str.split(separator, maxsplit)
Parameters used:
- separator: It is the delimiter. This parameter will specify where the method will split the string at which separator. By default, this parameter takes any white space as the separator if users do not pass any delimiter.
- maxsplit: It indicates a number. It helps users split the string into a maximum provided number of times. By default, the parameter specifies no limit when users do not pass any value in the parameter, i.e., -1.
On the other hand, the join() method allows users to join the elements that the split() method separated using separators. The method merges the split elements of a string and returns a new Python string. So, in the following example, we will see how these methods help to separate the whitespaces and remove them:
Syntax:
string_name.join(iterable)
This method accepts only one parameter:
- Iterable: This parameter specifies those data structures that can return their members one at a time.
For instance, String, List, Tuple, Dictionary, and Set
Code Snippet:
def demo(a):
return "".join(a.split())
a = ' This is Python space '
print(demo(a))
Output:
Explanation:
In this example, we used the split() method to break the string into separate elements, specifying the whitespaces with a separator. Then, we used the join() method that returns a new string concatenating with the string elements of iterable.
Method 4: Using sub() function or Regex in Python
Nothing can be easier than specifying a string order with characters using regular expressions. It is a unique string of characters used for searching, manipulating, and editing any string in Python.
Here, users will use the sub() function of the re (regular expression) module to replace all occurrences specified by a string pattern with a new Python string. The sub() is short for a substring.
Syntax:
re.sub(pattern, repl, string, count=0, flags=0)
Parameters used:
- pattern: This parameter specifies the pattern users want to replace.
- repl: This parameter will replace the leftmost non-overlapping pattern in the string by the replacement repl.
- count: Users can specify the number of pattern occurrences they want to replace with this count parameter. It is optional. By default, the parameter replaces all the occurrences of the specified pattern.
The regular expression used:
pattern= r"^\s+"
Here, the characters define:
r: indicates raw string notation for regular expression
\s: matches whitespace characters.
+: will correspond to one or more numbers of whitespace characters.
^(Caret): allows matching the start of a string
Code Snippet:
import re
def demo(a):
pattern = re.compile(r'\s+')
return re.sub(pattern, '', a)
a = ' This is Python space '
print(demo(a))
Output:
Explanation:
In the above example, using the re.sub() function, we passed a regular expression as the pattern. Then, the sub() function replaces all the whitespaces with black spaces and thus returns a new string with no space.
Method 5: Using reduce() function in Python
Users can also use the reduce() function to apply a particular function passed in its argument. It will list elements mentioned in the sequence users will specify.
Syntax:
functools.reduce(function, iterable[, initializer])
Parameters used:
- function: This parameter takes a function that accepts two more parameters, returning a single value. The first parameter is an accumulated value, and the second parameter is a current value from the iterable.
- iterable: This parameter specifies the sequence of values users specify to reduce.
- initializer: Users can use this parameter to provide an initial value for the accumulated result. It is optional. By default, the method returns the first element of the iterable as the initial value when users do not specify any initialize.
Code Snippet:
from functools import reduce
def demo(str):
return reduce(lambda p, q: (p + q) if (q != " ") else p, a, "");
a = ' This is Python space '
print(demo(a))
Output:
Method 6: Using lstrip() method to remove whitespaces from string
Users can get a copy of a string after removing all the leading characters using this method. The method will remove based on the string parameter passed. If users do not pass any parameter, it removes leading spaces.
Syntax:
string.lstrip(characters)
It accepts only one parameter:
- characters: This parameter specifies the set of characters the method will remove as leading characters. By default, for removing the characters, the parameter uses space. It is optional.
Code Snippet:
str =" This is Python space "
print (str.lstrip())
Output:
Explanation:
As you can see in the output console, the method has removed only the leading spaces from the string. It them returned a copy of all leading characters.
Method 7: Using rstrip() method to remove whitespaces from string
Users can get a copy of a string after removing all the trailing characters using this method. The method will remove based on the string parameter passed. If users do not pass any parameter, it removes trailing spaces.
Syntax:
string.rstrip([chars])
It accepts only one parameter:
- chars: This parameter specifies a string with a set of characters users want to remove.
Code Snippet:
str =" This is Python space "
print (str.rstrip())
Output:
Explanation:
As you can see in the output console, the method has removed only the trailing spaces from the string. It then returned a copy of the Python string with trailing whitespaces removed.
Method 8: Using itertools.filterfalse() method
The Python Itertools is the inbuilt module. Using this module, users can efficiently regulate the iterators. These allow the creation of iterables to iterate through lists and strings. Here, we will use the One such Itertools function filterfalse() to remove whitespaces from strings.
Syntax:
filterfalse(function or None, sequence) --> filterfalse object
Parameters used:
- function: It specifies the function users will pass into the method.
- sequence: This parameter specifies a list of integers.
Code Snippet:
import itertools
def demo(str):
res = list(itertools.filterfalse(lambda x: x == ' ', str))
return ''.join(res)
str = " Let us remove spaces "
print(demo(str))
Output:
Explanation:
In this code sample, we imported the Itertools module to use the filterfalse() method to get only those elements that return false for the passed function. Then, we joined the elements to get the resultant new string.
Method 9: Using isspace() method in Python
Python String isspace() method returns output based on what string characters it gets in the string. If the string contains all characters as whitespace, it returns True. Otherwise, It returns "False." Users can use the method to check if the parameters contain all whitespace characters, such as:
- ' ' for Space
- '\f' for Feed
- '\n' for Newline
- '\r' for Carriage return
- '\t' for Horizontal tab
- '\v' for Vertical tab
Syntax:
string.isspace()
Code Snippet:
def demo(str):
a = ""
for i in str:
if(not i.isspace()):
a+=i
return a
str = ' Is this a space? '
print(demo(str))
Output:
Explanation:
In this code snippet, we have taken a function "demo." Then, we took a string as the argument and a for loop to iterate through the string. The inspace() method searches for whitespace and skips the concatenation of the string character. Else we assigned them.
Method 10: Using map() and lambda() functions
Using the map function, users can iterate over the string elements with the function as its parameter. It returns a map object as an iterator.
Syntax:
map(fun, iter)
Parameters used:
- fun: This parameter specifies a function to which the map passes each element of a given iterable.
- iter: It specifies the iterable items which the method will map mapped.
Code Snippet:
str = ' This is Python '
str = ''.join(list(map(lambda a: a.strip(), str.split())))
print(str)
Output:
Explanation:
Here, we have specified a string variable with whitespace. We used the split() method to divide the string input into a list of substrings.
Then, we used the strip() method to remove all the leading and trailing whitespaces from each substring. The map() and its lambda function convert the object into a list.
Then, we used the join() method to join all the elements of the list of substrings into a single string. Lastly, we assigned the resulting string to a new variable. We printed the final string variable to get the desired output removing all the whitespaces.
Method 11: Using regex.findall() method for removing all the whitespace
This regex.findall() method returns all non-overlapping that match the given pattern in a string as a list of strings. The method scans the string from the left to the right direction.
Code Snippet:
import re
def demo(string):
return ''.join(re.findall(r'[a-zA-Z]+', str))
str = ' Let us know Python '
print(demo(str))
Output:
Explanation:
We used the demo() function with a regular expression in the above code sample. It eliminates all the whitespace characters from a given string.
The method first searches all the alphabetic non-whitespace characters in the input string using the findall() method. Then, we further proceeded by concatenating the substring elements using the join() method.
Users can term the user-defined demo() function as the driver program. We constructed a string variable called str which contains whitespace characters.
Method 12: Using NumPy
Code Snippet:
import NumPy as np
def demo(str):
return np.char.replace(str, ' ', '')
str = ' Here, we use NumPy '
print(demo(str))
Output:
Explanation:
Here, we have imported the NumPy module as "np." Then, we initialized a function "demo" and used the demo() function to replace all occurrences of whitespaces in the input string with an empty string and returned the desired string.
Method 13: Using a loop and join() method
Code Snippet:
str = " Make this an example "
res = ""
for i in str:
if i != " ":
res += i
str = "".join(res)
print(str)
Output:
Explanation:
Here, we have initialized a string with whitespaces. Then, we used a for loop to traverse through the string. Then, we further proceeded by concatenating the substring elements using the join() method.
Conclusion
This article depicts a blueprint of all thirteen methods and functions available with their code snippets allowing users to remove the specified characters. You can use the methods and their parameters to pass the whitespace characters you want to remove from the string.
These techniques are easy to implement, and the above syntaxes will help you proceed with their structures to avoid any errors.