Python string | strip()
strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed).
Syntax:
string.strip([chars]) Parameter: There is only one optional parameter in it: 1)chars - a string specifying the set of characters to be removed. If the optional chars parameter is not given, all leading and trailing whitespaces are removed from the string. Return Value: Returns a copy of the string with both leading and trailing characters removed.
# Python3 program to demonstrate the use of # strip() method string = " geeks for geeks " # prints the string without stripping print(string) # prints the string by removing leading and trailing whitespaces print(string.strip()) # prints the string by removing geeks print(string.strip(' geeks')) |
Output:
geeks for geeks geeks for geeks for
Errors:
There is a runtime error when we try to strip anything except a string. The system gives a output showing
# Python3 program to demonstrate the use of # strip() method error string = " geeks for geeks "list =[1, 2, 3] # prints the error message print(list.strip()) |
Output:
Traceback (most recent call last):
File "/home/1bdead5a6ad1dbb0db1c6a2663874e4c.py", line 8, in
print(list.strip())
AttributeError: type object 'list' has no attribute 'strip'
Practical application:
Given a string remove occurrence of word “The” from the beginning and the end.
# Python3 program to demonstrate the practical application # strip() string = " the King has the largest army in the entire world the" # prints the string after removing the from beginning and end print(string.strip(" the")) |
Output:
King has the largest army in the entire world
Recommended Posts:
- Python String | strip()
- Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
- numpy string operations | strip() function
- Python | Pandas Series.str.strip(), lstrip() and rstrip()
- Python | Check if given string can be formed by concatenating string elements of list
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Check if string ends with any string in given list
- Python | Sorting string using order defined by another string
- Python | Check if a given string is binary string or not
- String slicing in Python to rotate a string
- Python String
- Python String | max()
- Python | Add one string to another
- Python String | min()
- Python String | find()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Vishalmast



