Python String strip() Function with EXAMPLE

What is Python strip()?

Python strip() function is a part of built-in functions available in the Python library. The strip() method removes given characters from start and end of the original string. By default, strip() function removes white spaces from start and end of the string and returns the same string without white spaces.

In this Python tutorial, you will learn:

Syntax of the strip() method

string.strip([characters])

Parameters

Return Value

The Python String strip() will return:

Examples of strip() Function in Python

Example 1: strip() Method in Python

str1 = "Welcome to gtupapers!"
after_strip = str1.strip()

Output:

Welcome to gtupapers!

Example 2: strip() on Invalid Data Type

The Python String strip() function works only on strings and will return an error if used on any other data type like list, tuple, etc.

Example when used on list()

mylist = ["a", "b", "c", "d"]
print(mylist.strip()) 

The above will throw an error :

Traceback (most recent call last):
  File "teststrip.py", line 2, in <module>
    print(mylist.strip())
AttributeError: 'list' object has no attribute 'strip'

Example 3: strip() Without character parameter

str1 = "Welcome to gtupapers!"
after_strip = str1.strip()
print(after_strip)

str2 = "Welcome to gtupapers!"
after_strip1 = str2.strip()
print(after_strip1)

Output:

Welcome to gtupapers!
Welcome to gtupapers!

Example 4: strip() Passing character parameters

str1 = "****Welcome to gtupapers!****"
after_strip = str1.strip("*")
print(after_strip)

str2 = "Welcome to gtupapers!"
after_strip1 = str2.strip("99!")
print(after_strip1)
str3 = "Welcome to gtupapers!"
after_strip3 = str3.strip("to")
print(after_strip3)

Output:

Welcome to gtupapers!
Welcome to Guru
Welcome to gtupapers!

Why Python strip() function is used?

Here, are reasons for using Python strip function

Summary:

 

YOU MIGHT LIKE: