Python String strip() Method Tutorial

In this section, we will learn what String strip() method is and how to use it in Python.

What is String strip() Method in Python?

The Python string strip() method is used to strip the white spaces from both sides of a string value.

This means if the target string value has white spaces on both sides, then calling this method will clear out those spaces.

Note that by default, this method will remove the white spaces from both sides, but it also can take an optional argument that accepts a different type of character to be removed from the sides of a string value.

For example, if the sides contain 0s and we want to remove that, then we can put the value 0 as the argument of this method and so this time the method will remove the 0s from the sides of this string.

Python String strip() Method Syntax:

string.strip(character)

String strip() Method Parameter

The method takes one optional argument and that is the character (or a set of characters) we want to remove from the sides of a string value. The default value is set to white space.

String strip() Method Return Value

The return value of this method is a new string with its sides are removed from white spaces (or removed from the value specified as the argument of the method).

Note: the method does not change the original content but instead will create a new one and return that as a result.

Example: python trim string

s1 = " My name is John Doe "

print(s1.strip())

Output:

My name is John Doe

Example: python remove newline from string

s1 = "\n\n\n\n\n\nMy name is John Doe\n\n\n\n\n\n"

print(s1.strip())

Output:

My name is John Doe

Example: python remove character from string

s1 = "*************My name is John Doe**************"

print(s1.strip("*"))

Output:

My name is John Doe
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies