Python String strip: How to Remove Whitespace In String
The strip() method removes characters from both left and right based on the argument. If the character argument is not passed as a parameter, then all the leading and trailing whitespaces are removed from the string.
Python String strip()
Python strip() is an inbuilt function that returns the copy of a string with both leading and trailing characters removed based on the string argument passed.
If you are looking for a solution to how to remove whitespace in Python or remove any specific character from string then Python string strip() is the answer.
The syntax of the String.strip() method is the following.
The character is an optional parameter which is the string specifying the set of characters to be removed. If the character argument is not provided, all leading and trailing whitespaces are removed from the string.
The strip() method returns the copy of the string with both leading and trailing characters stripped.
See the following example.
# app.py data = ' Winter is coming!! ' print(data.strip())
Above code, we have put the space at the starting of the string and put two spaces at the end of the string.
See the output.
So, in the above example, the spaces from a string are removed from the start and end of the String.
When the combination of characters in the character argument mismatches the character of a string in the left, it stops removing the leading characters.
Similarly, when the combination of characters in the character argument mismatches a character of the string in the right, it stops removing the trailing characters.
# app.py data = 'winter is coming!' print(data.strip('wi')) string = 'appdividend is awesome' print(string.strip('app'))
See the output.
So, in the above example, we have passed arguments that are matched with a string, and it strips from the string and returns the remaining string.
Remember that, it will not remove the spaces from between the string characters. It will remove the space at the start and end of the string.
Finally, the Python String strip() function is over.