Python String strip() Method

Strips leading and trailing characters

Usage

The strip() method removes whitespace from the beginning (leading) and end (trailing) of the string by default.

By adding chars parameter, you can also specify the characters you want to strip.

Syntax

string.strip(chars)

Python string strip() method parameters
ParameterConditionDescription
charsoptionalA list of characters to be removed from the string

Return Value

The method return a copy of the string with the leading and trailing characters removed.

Strip Whitespace

By default, the method removes leading and trailing whitespace.

Example: Strip leading and trailing whitespace

S = '   Hello, World!   '
x = S.strip()
print(x)

Input:

   Hello, World!   

Stripped:

   Hello, World!   

Output:

Hello, World!

Newline '\n', tab '\t' and carriage return '\r' are also considered as whitespace characters.

Example: Strip newline ‘\n’, tab ‘\t’ and carriage return ‘\r’

S = '  \t Hello, World! \n\r '
x = S.strip()
print(x)

Input:

  \t Hello, World! \n\r 

Stripped:

  \t Hello, World! \n\r 

Output:

Hello, World!

Strip Characters

By adding chars parameter, you can also specify the character you want to strip.

Example: Strip single character ‘a’

S = 'aaabaaaa'
x = S.strip('a')
print(x)

Input:

aaabaaaa

Stripped:

aaabaaaa

Output:

b

Strip Multiple Characters

The chars parameter is not a prefix or suffix; rather, all combinations of its values are stripped.

In below example, strip() would strip all the characters provided in the argument i.e. ‘c’, ‘m’, ‘o’, ‘w’, ‘z’ and ‘.’

Example: Strip multiple characters

S = 'www.example.com'
x = S.strip('cmowz.')
print(x)    

Input:

www.example.com

Stripped:

www.example.com

Output:

example

More About strip() Method

Characters are removed from both ends until reaching a string character that is not contained in the set of characters in chars.

Example:

S = 'xxxxSxxxxSxxxx'
x = S.strip('x')
print(x)

Input:

xxxxSxxxxSxxxx

Stripped:

xxxxSxxxxSxxxx

Output:

SxxxxS

Explanation:

Python Strip Method Example Explanation

Here is another example:

Example:

S = '... - Version 3.2 Model-32 ...'
x = S.strip('.- ')
print(x)

Input:

... - Version 3.2 Model-32 ...

Stripped:

... - Version 3.2 Model-32 ...

Output:

Version 3.2 Model-32