What does .strip do in python?

The strip() function removes the leading and trailing character from the string based on the characters passed as an argument and returns a copy of the string. If no character is passed as a parameter the strip() function by default removes leading and trailing white spaces.

The syntax for the strip() function is given below

#syntax:
string.strip([chars])

Example 1: Using the strip() function without any parameters.

string_1 = " Welcome To Python  "
print("string_1: ", string_1)
string_2 = string_1.strip()
print("string_2: ", string_2)

Output

string_1:   Welcome To Python  
string_2:  Welcome To Python

Example 2: Removing a word from a string

string_1 = "  Python Programming"
print("string_1: ", string_1)
string_2 = string_1.strip('Programming')
print("String_2: ", string_2)

The above code returns the output as

string_1:    Python Programming
String_2:    Python

Example 3: Consider a string_1 = " Python Programming". We pass whitespace, 'o', 'n', 'P' as a parameter to the strip function. The program removes the leading whitespace and character 'P' from string_1 and returns the string. The character 'o' and 'n' were not removed as they were not present in the leading or trailing ends.

string_1 = "  Python Programming"
print("string_1: ", string_1)
string_2 = string_1.strip('[ onP]' )
print("String_2: ", string_2)

Output

string_1:    Python Programming
String_2:  ython Programming
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions