what is the use of strip() in python

 What is the use of strip() in python

there are various way in which we can explain strip 
  • When we use strip() then it removes all whitespaces from the beginning and the end of the string because there is nothing between the brackets.
  • strip() is an inbuilt function in Python programming language that is used for removing beginning and ending character which is passed between the brackets.

Syntax:

string.strip([chars])

Example:-

string = """     geeks for geeks     """ 
  
# prints the string without stripping
print(string) 
  
# prints the string by removing leading and trailing whitespaces
print(string.strip())   
  
# prints by removing geeks
print(string.strip(' geeks'))


Output: geeks for geeks geeks for geeks for

by the above example I am sure you would have understood but then also let see another example.

Example:-

  
string1 = 'geeks for geeks'
# without striping.
print(string1)
  
# remove from original string at both its ends.
string2 = 'ekgs'
  
# Print string after striping string2 from str1 from beginning and end.
print(string1.strip(string2))

Output: geeks for geeks for

The best use of strip is in this program shown below:-


for i in range(int(input())): n = input().strip(); counts = n.count('4') + n.count('7') print(len(n)-counts)

In this program advantage of using strip is that when the input is given, the whitespaces in the beginning and end are removed. 

 

Post a Comment

0 Comments