Example of Python strip method

Python 3 strip method Example :

Python strip() method is used for removing leading and trailing characters. It doesn’t modify the original string. Actually it can’t modify the string because it is immutable. It creates one copy of the string by removing the leading/trailing characters and returns that string.

In this tutorial, we will learn how to use strip method with an example.

Syntax of strip method :

The syntax of strip() is as below :

str.strip([chars])

Parameter and return value :

It takes one optional parameter chars. If this argument is not provided, it will remove all leading and trailing whitespaces from the string.

chars is a string. If you pass this argument, it will remove all characters in that string from the leading and trailing.

It returns the new modified string.

Example of strip without chars :

The below example uses strip without the parameter chars.

given_str = "     codevscolor.com     "
new_str = given_str.strip()

print("Given string :-{}-".format(given_str))
print("Modified string :-{}-".format(new_str))

Output :

Given string :-     codevscolor.com     -
Modified string :-codevscolor.com-

Python strip without chars

I am using two - at the start and end of the string to identify the blank spaces around it.

Example of strip with chars :

given_str = "https://www.codevscolor.comxyz"
new_str = given_str.strip(":/thpsxyz")

print("Given string :-{}-".format(given_str))
print("Modified string :-{}-".format(new_str))

It will print the below output :

Given string :-https://www.codevscolor.comxyz-
Modified string :-www.codevscolor.com-

Here, we are passing :/thpsxyz as the argument. It will remove all characters :, /, t, h, p, s, x, y, z from the start and end of the string. It will stop if it finds any other character. For example, s is in the middle of the string but it is not removing that.

Python strip with chars

strip() is one of the most widely used methods. It comes handy to quickly remove unwanted characters from the start and end of a string.

Similar tutorials :

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊