Python strip() Method

Python 字符串Python Strings


Description

Python strip() method removes specified characters (space or newline by default) or character sequences from the beginning and end of a string.

Note:This method can only delete characters at the beginning or end, not characters in the middle.

Syntax

Syntax of the strip() method:

str.strip([chars]);

Parameters

  • chars -- The specified sequence of characters to remove from the beginning and end of the string.

Return Value

Returns a new string generated by removing the specified characters from the beginning and end of the string.

Examples

The following examples demonstrate how to use the strip() function:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- str = "00000003210Example01230000000"; print str.strip( '0' ); # Remove leading and trailing character 0 str2 = " Example "; # Remove leading and trailing spaces print str2.strip();

The output of the above examples is as follows:

3210Example0123
Example

From the results, you can notice that the characters in the middle part are not removed.

The following example demonstrates that characters are removed as long as the beginning and end contain characters from the specified character sequence:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- str = "123abcexample321" print (str.strip( '12' )) # The character sequence is 12

The output of the above example is as follows:

3abcexample3

Python 字符串Python Strings

Other Extensions