In this post, we will see how to remove whitespace from String in Python.
There are multiple ways to do it.
Table of Contents
Remove all whitespace from String
You can use String’s replace method to remove all whitespaces from String in Python.
1 2 3 4 5 |
str = " Hello Java2blog " str= str.replace(' ','') print(str) |
Output:
Remove leading and trailing whitespaces from String
You can use String’s strip method to remove leading and trailing whitespace whitespaces from String in Python.
1 2 3 4 5 |
str = " Hello Java2blog " str= str.strip() print(str) |
Output:
Remove leading whitespaces from String
You can use String’s strip method to remove leading whitespace whitespaces from String in Python.
1 2 3 4 5 |
str = " Hello Java2blog " str= str.lstrip() print(str) |
Output:
Remove trailing whitespaces from String
You can use String’s strip method to remove trailing whitespace whitespaces from String in Python.
1 2 3 4 5 |
str = " Hello Java2blog " str= str.rstrip() print(str) |
Output:
Remove all whitespace characters (space, tab, newline, and so on) from String
You can use split and join to remove all whitespace
To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:
1 2 3 4 5 |
str = " Hello Java2blog " str = ''.join(str.split()) print(str) |
Output:
That’s all about how to remove whitespace from String Python