Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python strip() method

Python strip() method

Python Strings Python Strings


Description

The Python strip() method removes specified characters (defaulting to spaces or newlines) or sequences of characters from the beginning and end of a string.

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

Syntax

Syntax of the strip() method:


str.strip([chars]);

Parameters

Return Value

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

Example

The following example shows how to use the strip() function:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

str

=

"

00000003210Runoob01230000000

"

;

print

str

.

strip

(

'

0

'

)

;

Remove the leading and trailing character 0

str2

=

"

Runoob

"

;

Remove leading and trailing spaces

print

str2

.

strip

(

)

;

The output of the above example is:


3210Runoob0123
Runoob

From the result, you can notice that characters in the middle were not removed.

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

Example

#!/usr/bin/python

-- coding: UTF-8 --

str

=

"

123abcrunoob321

"

print

(

str

.

strip

(

'

12

'

)

)

The character sequence is 12

The output of the above example is:


3abcrunoob3

Python Strings Python Strings