Open In App

Python string | strip()

Last Updated : 08 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python String strip() is an inbuilt function in the Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). This article will examine the many features and use cases of the strip() method to give you a thorough grasp of how to use it successfully in your Python programs.

Python strip() Method Syntax

Syntax: string.strip([chars])

Parameter: There is only one optional parameter in it. 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.

Purpose of the Python Strip() Function

When a developer wishes to remove characters or whitespaces from the beginning or end of a string, the Strip() function in Python comes in handy. Let’s take a closer look at it: 

  • The strip() function assists in removing characters from the beginning or end of a string for characters supplied as arguments to the strip() function ().
  • If the string has no whitespaces and the characters argument is not supplied, the string is returned as is.
  • It is also beneficial to eliminate whitespaces from the beginning and end of the text.
  • If the string contains whitespaces and no character arguments are supplied, the string will be returned after discretizing the whitespaces.

String strip() in Python Example

In Python, the strip() method is used to remove leading and trailing whitespace characters (spaces, tabs, and newlines) from a string. It returns a new string with the whitespace characters removed. The original string remains unchanged.

Example

Python3




my_string = "   Hello, world!   "
stripped_string = my_string.strip()
  
print(stripped_string)


Output

Hello, world!

Python Stripping String with Strip() function

In this example, we will Python String Trim and we have used a string and we have applied the strip() function with a string and without a string.

Python3




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

Python Stripping Specific Character with Strip() Function

In this example, we will Python String Trim and we have used the strip() function to remove a specific set of characters from a string.

Python3




# Python Program to demonstrate use of strip() method 
  
str1 = 'geeks for geeks'
# Print the string without stripping.
print(str1)
  
# String whose set of characters are to be
# remove from original string at both its ends.
str2 = 'ekgs'
  
# Print string after stripping str2 from str1 at both its end.
print(str1.strip(str2))


Output

geeks for geeks
for

Python Removing Whitespaces with Strip() function

In this example, we will Python String Trim and we have used the strip() function to remove the whitespaces from both ends of a string.

Python3




# Python Program to demonstrate use of strip() method without any argument
str1 = """    geeks for geeks    """
  
# Print the string without stripping.
print(str1)
  
# Print string after removing all leading 
# and trailing whitespaces.
print(str1.strip())


Input

    geeks for geeks     

Output

geeks for geeks

Python Removing NewLine using Strip() Function

In this example, we will Python String Trim and we are using the strip() function to remove the newline characters from a string.

Python3




string = "\nHello, World!\n"
new_string = string.strip()
print(new_string)


Output

Hello, World!

Practical Application

 Given a string remove the occurrence of the word “the” from the beginning and the end. we will Python String Trim.

Python




# Python3 program to demonstrate the practical application
# strip() 
  
string = " the King has the largest army in the entire world the" 
  
# strip function works on characters and removes characters till it sees, 
# the last or beginning characters mentioned in the function has been removed
print(string.strip(" eht"))


Input

the King has the largest army in the entire world the

Output

King has the largest army in the entire world


Previous Article
Next Article

Similar Reads

Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Python - Strip front and rear Punctuations from given String
Given a string strip rear and front punctuations. Input : test_str = '%$Gfg is b!!est(*^' Output : Gfg is b!!est Explanation : Front and rear punctuations are stripped. Input : test_str = '%Gfg is b!!est(*^' Output : Gfg is b!!est Explanation : Front and rear punctuations are stripped. Method #1 : Using punctuation() + loop In this, we use punctuat
6 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 min read
numpy string operations | strip() function
numpy.core.defchararray.strip(arr, chars=None) is another function for doing string operations in numpy. It returns a copy with the leading and trailing characters removed for each element in arr. Parameters: arr : array_like of str or unicode. char : [str or unicode, optional] the set of characters to be removed. If omitted or None, it removes whi
2 min read
Python | Pandas Series.str.strip(), lstrip() and rstrip()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas provide 3 methods to handle white spaces(including New lines) in any text data. As can be seen in the name, str.lstrip() is used
4 min read
Wand strip() function - Python
The strip() function is an inbuilt function in the Python Wand ImageMagick library which is used to strip an image of all the profiles and comments. Syntax: strip() Parameters: This function does not accepts any parameter.Return Value: This function returns the Wand ImageMagick object. Original Image: Example 1: C/C++ Code # Import library from Ima
2 min read
Python Seaborn - Strip plot illustration using Catplot
Seaborn is a data visualization library that is based on matplotlib. A high-level interface is provided by seaborn for drawing informative and attractive statistical graphics. Seaborn Catplot is a new addition to seaborn that makes plotting easier and involves categorical variables. It is used to show the relation between categorical variables like
2 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Check if given string can be formed by concatenating string elements of list
Given a string 'str' and a list of string elements, write a Python program to check whether given string can be formed by concatenating the string elements of list or not. Examples: Input : str = 'python' lst = ['co', 'de', 'py', 'ks', 'on'] Output : False Input : str = 'geeks' lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz'] Output : True Approach #1
5 min read
Article Tags :
Practice Tags :