Remove whitespace from String Python

Previous
Next

In this post, we will see how to remove whitespace from String in Python.

There are multiple ways to do it.


Remove all whitespace from String

You can use String’s replace method to remove all whitespaces from String in Python.

str = " Hello Java2blog " str= str.replace(' ','') print(str)

Output:

HelloJava2blog

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.

str = " Hello Java2blog " str= str.strip() print(str)

Output:

Hello Java2blog

Remove leading whitespaces from String

You can use String’s strip method to remove leading whitespace whitespaces from String in Python.

str = " Hello Java2blog " str= str.lstrip() print(str)

Output:

Hello Java2blog

Remove trailing whitespaces from String

You can use String’s strip method to remove trailing whitespace whitespaces from String in Python.

str = " Hello Java2blog " str= str.rstrip() print(str)

Output:

Hello Java2blog

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:

str = " Hello Java2blog " str = ''.join(str.split()) print(str)

Output:

HelloJava2blog

That’s all about how to remove whitespace from String Python

Previous
Next

Add Comment