Python String strip() Method



The Python string strip() method is used to remove all the specified leading and trailing characters from the beginning and the end of a string. The method removes the leading characters from the beginning of the string first, followed by the trailing characters in the end. If a different character than the specified character is encountered, the method stops stripping.

The strip() method also removes the newline characters ‘\n' both from the beginning and the ending of the string, while stripping.

Syntax

Following is the syntax for Python String strip() method −

str.strip([chars]);

Parameters

  • chars − The characters to be removed from beginning or end of the string.

Return Value

This method returns a copy of the string in which all chars have been stripped from the beginning and the end of the string.

Example

When we pass a letter as the argument to the method, the return value will be the string with the leading and trailing occurrences of the letter stripped.

The following example shows the usage of Python String strip() method.

str = "0000000this is string example....wow!!!0000000";
print str.strip('0')

When we run above program, it produces following result −

this is string example....wow!!!

Example

If we give no arguments to the strip() method, the leading and trailing whitespaces will be stripped.

In the following program, we create a string " this is string example ", and call the strip() method with no arguments. The return value will contain the string with all the leading and trailing whitespaces stripped. −

str = "    this is string example         ";
print(str.strip())

The program above is executed to produce the following output −

this is string example

Example

This method is case-sensitive. When we pass a character argument to the method, it will not strip the same character with a different case.

In the following program, we are taking a string input "xxxxxXXXXX this is string example XXXXXxxxxx". Using the strip() method, we will only try to strip lowercased characters, so the argument passed is 'x'. The method starts stripping all leading and trailing 'x' characters but stops when it encounters 'X'; even though its the same letter but with different case.

str = "xxxxxXXXXX this is string example XXXXXxxxxx";
print(str.strip('x'))

If we compile and run the given program, the output is displayed as follows −

XXXXX this is string example XXXXX
python_strings.htm
Advertisements