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
- Using a for loop
- Using map() with a lambda function
- Using a list comprehension with the strip() method
- Conclusion

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
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.







You must be logged in to post a comment.