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!
Python string | strip()
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.