In this tutorial, we will discuss three different approaches to remove spaces in a string using Python. By the end of this guide, you will have a clear understanding of how to efficiently remove spaces from strings in Python.

Let’s get started!

Table of contents

  1. Using a for loop
  2. Using map() with a lambda function
  3. Using a list comprehension with the strip() method
  4. Conclusion
Remove Spaces in String in Python
Photo by Monstera Production on Pexels.com

Using a for loop

Example:1

s = 'KDnuggets,  is,  a,  fantastic,  resource'
a = s.split(',')
result = []
for item in a:
    result.append(item.strip())

print(result)

Output

['KDnuggets', 'is', 'a', 'fantastic', 'resource']


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Using map() with a lambda function

Example:2

s = 'KDnuggets,  is,  a,  fantastic,  resource'
a = list(map(lambda item: item.strip(), s.split(',')))
print(a)

Output

['KDnuggets', 'is', 'a', 'fantastic', 'resource']


** Process exited - Return Code: 0 **
Press Enter to exit terminal

Using a list comprehension with the strip() method

Example:3

s = 'KDnuggets,  is,  a,  fantastic,  resource'
a = [item.strip() for item in s.split(',')]
print(a)

Output

['KDnuggets',  'is', 'a', 'fantastic', 'resource']
** Process exited - Return Code: 0 **
Press Enter to exit terminal

Audio explanation

Removing spaces in a string

Conclusion

All three approaches will give the same output, which removes the whitespace around each item in the list. You can choose the approach that you find most readable convenient for your specific use case.