In Python, there are several methods for removing spaces from a string. This article aims to give a quick overview of the many functions available for removing whitespace from a string so let’s go and remove spaces from a string in python.
Remove Spaces from a String in Python
We can’t change the value of a Python String because it’s immutable. Any function that manipulates string values returns a new string, which must be explicitly assigned to the string otherwise the string value will remain unchanged.
Let’s imagine we have the following sample string: s = ‘ Hello World From Pankaj \t\n\r\tHi There
There are many types of whitespaces as well as newline characters in this string. Let’s have a look at some of the functions that can be used to eliminate spaces. strip() \sPython The strip() function removes leading and trailing whitespaces from a string.
s.strip() 'Hello World From Pankaj \t\n\r\tHi There'
Instead, use the lstrip() or rstrip() functions to remove only leading or trailing spaces.
To eliminate all whitespaces from the string, we can use replace(). Whitespace between words will also be removed by this function.
s.replace() 'HelloWorldFromPankaj\t\n\r\tHiThere' join() with split()
You can use the join() function in conjunction with the string split() function to remove all duplicate whitespaces and newline characters.
The string translate() function can be used to remove all whitespaces and newline characters from a string.
Read More: How To Split A-List In Python?