How to Remove Whitespace From String in Python?

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Removing whitespace from strings in Python is essential for data processing and formatting. This article explores various methods to achieve this, from using the replace() function to employing Python regex, ensuring efficient whitespace removal from strings in your Python code.

Methods to Remove whitespace from String in Python

To remove spaces from a string in Python, you can utilize several approaches, each suited to different scenarios and requirements:

  1. Using replace()
  2. Using translate()
  3. Using lstrip() function
  4. Using rstrip() function
  5. Using isspace() method
  6. Using Regex and itertools
  7. Using split() and strip() function
  8. Using NumPy

Remove whitespace from String in Python Using replace()

We can use the replace() function to replace all the whitespaces with an empty string value. The replace() function returns a string by replacing all instances of substring values with other substring values.

string replace() can be used by the following syntax:

Where old is the old substring you want to replace, new is the new substring that will replace the old substring, and the count is the optional parameter that indicates the number of times the new substring replaces the old substring. So in this process, we will successfully Remove Whitespaces from String.

Time Complexity: both best case and worst case is O(N)O(N) where N is the length of the string.

Space Complexity: O(N)O(N) as a new string of size N is created.

Example:

In this example, we pass the old parameter as " " and the new parameter as "" to the replace function.

Output

Remove whitespace from String in Python Using translate()

We can use the translate function for mapping all the whitespaces to an empty string and then translate all the mapping done using the maketrans() function to Remove Whitespaces from String.

Time Complexity : both best case and worst case is O(N)O(N) where N is the length of the string.

Space Complexity : O(N)O(N) as a new string of size N is created.

Example:

In this example, we use the maketrans() function to map and replace all the whitespaces with an empty string into an abject dictionary. That dictionary is then translated to the final output string using the translate() function.

Output:

Remove Spaces from a String in Python Using lstrip() Function

The lstrip() function in Python is used to create a new string by removing leading whitespace (spaces at the beginning of a string). This function is particularly useful when you need to clean up the beginning of a string for formatting or processing purposes.

Here's an example demonstrating the use of lstrip() to remove leading spaces from a string:

Output:

example.com www.

In this example, lstrip() effectively removes all the spaces before "example.com", resulting in a string that starts immediately with the text.

Remove Spaces from a String in Python Using rstrip() Function

The rstrip() function in Python creates a new string by removing trailing whitespaces (spaces at the end of a string), which can be particularly useful for cleaning up the end of strings where extra spaces are not needed or desired.

Here's how you can use the rstrip() function to remove spaces from the right side of a string:

Output:

Example string with trailing spaces

The rstrip() function is straightforward and effective for removing unwanted spaces from the right end of a string, making string manipulation in Python simpler and more efficient.

Remove Spaces from a String in Python Using isspace() Method

This method helps in identifying whitespace characters within a string, enabling their removal through a simple but effective approach.

Here's how you can use the isspace() method to trim extra spaces from a string:

  1. Initialize an empty string to store the result.
  2. Iterate over each character in the original string using a for loop.
  3. Check each character with the isspace() method to determine if it is a whitespace character.
  4. If a character is not a whitespace, concatenate it to the result string; otherwise, skip it.

Below is a Python function that demonstrates this method:

Output:

python

Remove Spaces from a String in Python Using Regex and itertools

To strip spaces from a string in Python, combining Regular Expressions (Regex) with itertools.filterfalse() offers a concise and effective solution. Regex identifies and removes all whitespace, while itertools.filterfalse() filters out any remaining spaces, leaving behind a clean string.

Here's a simplified Python code example:

Remove Spaces from a String in Python Using split() and strip() Functions

To remove all spaces from a string in Python, combining the split() and strip() functions offers a straightforward approach. Here's how it works:

  • First, use the split() function to divide the string into a list of words or characters, effectively separating them based on whitespace.
  • Next, apply the strip() function to each element in the list to remove any leading or trailing spaces. This can be efficiently done using the map() function alongside a lambda expression.
  • Finally, reassemble the list into a single string without any spaces by using the join() function.

Here's a concise example to illustrate this method:

This method is effective for strings where spaces need to be eliminated entirely, providing a clean, space-free string as output.

Remove Spaces from a String in Python Using NumPy

To eliminate spaces from a string in Python effectively, NumPy offers a straightforward and efficient approach. By utilizing the np.char.replace function, you can seamlessly replace all occurrences of spaces with an empty string, thus removing them from the string. Here's a concise example demonstrating this method:

Conclusion

  1. Python provides multiple methods for removing spaces from strings, including replace(), translate(), and strip() functions.
  2. The replace() function efficiently eliminates all spaces by replacing them with an empty string.
  3. lstrip() and rstrip() offer targeted removal of leading and trailing spaces, respectively.
  4. Advanced techniques, such as using regex or NumPy, cater to complex patterns and large-scale data processing.
  5. Combining split() and strip() ensures thorough space elimination, yielding clean, space-free strings.

Explore Scaler Topics Python Tutorial and enhance your Python skills with Reading Tracks and Challenges.