Python strip: How to Remove Whitespace in String

1
207
Python String Strip() Function Tutorial With Example

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 strip

Python strip() is a built-in string function that returns the copy of a string with both leading and trailing characters removed based on the argument passed.

To remove whitespace in Python or any specific character from a string, use the string strip() function.

Syntax

The syntax of the String.strip() method is the following.

string.strip([character])

Parameters

The character is an optional parameter, 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 String copy with both leading and trailing characters stripped.

Example

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.

Python String Strip Example

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 on the left, it stops removing the leading characters.

Similarly, when the combination of characters in the character argument mismatches a character of the String on 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.

Python String strip() Tutorial

So, in the above example, we have passed arguments matched with a string, which strips from the String and returns the remaining String.

Remember that it will not remove the spaces between the string characters. Instead, it will remove the space at the start and end of the String.

That’s it for this tutorial.

1 Comment

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.