Python Program to Remove All Whitespace from String
You can remove all whitespace from a string in Python using
''.join(s.split()), which splits the string by whitespace and joins it back without spaces.Examples
Inputhello world
Outputhelloworld
Input Python is fun
OutputPythonisfun
Input
Output
How to Think About It
To remove all whitespace, think of breaking the string into parts wherever there is space, then putting those parts back together without any spaces. This way, all spaces, tabs, or newlines are removed.
Algorithm
1
Get the input string.2
Split the string into parts using whitespace as separator.3
Join all parts together without any spaces.4
Return or print the joined string.Code
python
s = input('Enter a string: ') result = ''.join(s.split()) print(result)
Output
Enter a string: Python is fun
Pythonisfun
Dry Run
Let's trace the input ' Python is fun ' through the code
1
Input string
' Python is fun '
2
Split string by whitespace
['Python', 'is', 'fun']
3
Join parts without spaces
'Pythonisfun'
4
Print result
Pythonisfun
| Step | Operation | Value |
|---|---|---|
| 1 | Input string | ' Python is fun ' |
| 2 | Split by whitespace | ['Python', 'is', 'fun'] |
| 3 | Join parts | 'Pythonisfun' |
| 4 | Output | Pythonisfun |
Why This Works
Step 1: Splitting the string
Using split() without arguments breaks the string at all whitespace, including spaces, tabs, and newlines.
Step 2: Joining without spaces
Using ''.join() combines the list of words back into one string without adding any spaces.
Alternative Approaches
Using replace() method
python
s = input('Enter a string: ') result = s.replace(' ', '') print(result)
This removes only space characters, not tabs or newlines.
Using regular expressions
python
import re s = input('Enter a string: ') result = re.sub(r'\s+', '', s) print(result)
This removes all kinds of whitespace including spaces, tabs, and newlines.
Complexity: O(n) time, O(n) space
Time Complexity
Splitting and joining the string each take linear time proportional to the string length.
Space Complexity
Extra space is used to store the list of words and the final joined string.
Which Approach is Fastest?
Using replace() is faster but only removes spaces. Using split() and join() or regex handles all whitespace but with slightly more overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| split() + join() | O(n) | O(n) | Removing all whitespace types |
| replace(' ', '') | O(n) | O(n) | Removing only spaces, faster |
| regex sub | O(n) | O(n) | Removing all whitespace with pattern flexibility |
Use
''.join(s.split()) to remove all whitespace easily and reliably.Beginners often use
replace(' ', '') which misses tabs and newlines.