Strip Function in Python – A Complete Overview with Examples

Updated on October 17, 2024

Article Outline

The strip() function is one of the valid string methods for Python objects. Its main function is to strip away any characters from the string in front of it, in front of the first character, and at the end of it. By default, it strips white space characters only, including space, tab, and newline. But here, we can pass an argument to the function and say which characters must be removed.

What is the strip() in Python?

The strip() method is a string function that removes whitespaces from both the beginning and end of the string. These include spaces, tabs, newlines, and all the other forms of White spaces. It might be crucial to mention that the strip() method does not affect the string from which it is called. It returns with the specified characters.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Syntax of strip() in Python

 

The syntax of the strip() in Python is as follows.

 

str.strip(del_string_name)

 

Also Read: What is a List in Python?

Parameters of the strip() function in Python

This function accepts only one parameter.

 

  • del_string_name: This parameter specifies the set of characters to be removed from the beginning and end of the string. If this parameter is not provided, strip() will remove whitespace characters (spaces, tabs, newlines, etc) by default.

Return Value of strip() in Python

The strip() function returns a new string by replacing a few or no characters from the old string according to the specified functionality.

 

Also Read: Append Function in Python

Examples of strip() in Python

Without Parameters

 

This program doesn’t pass the parameter to the strip function. It removes whitespaces from the start and end. Let’s see the working example of this discussion.

 

Program  

text = "   Hello, World!   " strip_text = text.strip() print(strip_text)

Output

Hello, World!

Explanation: The following program demonstrates that no parameters are specified, so only the whitespaces are removed from the start and end of our input string.

With Parameters

 

The following program demonstrates the strip() function with parameters.

 

Program  

text = "###Hello, World###" stripped_text = text.strip("#") print(stripped_text)

Output

Hello, World

Explanation: The above program occurrence of “#” is removed from the string and returned as a new string without the “#.”

More Examples

 

Example 1: Strip Function with None

str = "     abcdef  " print(str.strip(None))

Output

abcdef

Example 2: The original String is not altered

str = "Voldemort Harry Potter Computer" print("Stripped string:",str.strip("a.p")) print("Original string:",str)

Output

Stripped string: Voldemort Harry Potter Computer Original string: Voldemort Harry Potter Computer

Example 3: Passing Substring as Parameter

 

We can also directly pass a substring to this parameter, as the order of characters in the del_string parameter is unimportant. This means that in the case of the strip() function, the substring will be removed on both ends of the string.

 

Program

myStr = "one six" paramStr = "one" print(myStr.strip(paramStr))

Output

six

Example 4: Python strip() on Invalid Data Type

The strip() function can only be applied to a string and can only accept a string as a parameter. If we apply the strip() function to an invalid data type, we will get an error stating that strip() is not defined for that data type.   a= 50 print("Stripped String =",a.strip(5))

Output

Traceback (most recent call last): File "E:ProgrammingJavaindex.py", line 2, in <module> print("Stripped String =",a.strip(5)) ^^^^^^^ AttributeError: 'int' object has no attribute 'strip'

Example 5: Python Stripping Specific Character with Strip() Function

The following program demonstrates the Strip() function.

Program

original_string = "xxxHello, World!xxx" stripped_string = original_string.strip('x') print("Original String:", original_string) print("Stripped String:", stripped_string)

Output 

Original String: xxxHello, World!xxx Stripped String: Hello, World!

Why is the Python Strip() Function Used?

The strip() function in Python is primarily used to remove unwanted characters or whitespace from the beginning and end of a string.

  • Cleaning Input Data: We can process user input; extra spaces, tabs, or newline characters can often be included inadvertently. The strip() function helps clean this input, ensuring only the relevant data remains.
  • Removing Specific Characters: The strip() function can take an optional argument that specifies a set of characters to remove from both ends of the string. This is very useful when eliminating specific characters rather than just whitespaces.
  • Enhancing Readability: The strip () function improves the readability of output by removing unnecessary characters from the beginning and end strings, making it easier for users to read and understand.
  • Preparing Data for Storage or Comparison: Striping extra whitespace strings can accurately compare or store data in a clear format.

 

Also Read: Top 50 Python Programming Examples

Conclusion

strip() function is a method to take the leading and trailing space (or any other character) off a string in a common way. This does not alter the original string or any character but returns a new string without these unwanted characters. It is useful when sanitizing user-submitted data or normalizing strings so there is no unwanted space or other character around the string.   The strip() does not use spaces as the default value; it involves a character argument, so it has more characters to deal with than just spaces. If you want to explore Python programming in detail, you can consider pursuing the Accelerator Program in Business Analytics and Data Science offered by Hero Vired in collaboration with eDX and Harvard University.

FAQs
The strip() function removes leading and trailing whitespace or specified characters from a string. It creates a new string with the unwanted characters removed from both ends.
No, strip() only removes characters from the beginning (leading) and end (trailing) of the string. The characters in the middle are unaffected
Yes, strip() is case-sensitive. Passing a specific character to remove will only remove characters that match the exact case.
No, strip() only removes whitespaces or specified characters from the beginning and end of the string. It does not affect whitespace within the string.
If strip() is called on a non-string type (like an integer or list), It will raise an AttributeError, as those types do not have a strip() method. It always ensures that the variable is a string before using strip().

Updated on October 17, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved