
Python strip() Function: Complete Guide with Examples
Python strip() Function: The Python strip() function is a built-in method that removes specified characters from the start and end of a string. By default, it removes whitespace characters. This guide will explain its syntax, parameters, return values, and practical examples.
What is Python strip()?
Python strip() Function: The strip() function is used to clean strings by removing unwanted characters from the beginning and end of the string. It is particularly useful for handling data with unnecessary spaces or symbols.
Syntax of strip() Method
python
string.strip([characters])
Parameters:
- characters (optional): The characters you want to remove from the start and end of the string.
- If no parameter is specified, the method will remove whitespace by default.
Return Value:
- Returns the original string with unwanted characters removed from the start and end.
- If there are no matching characters, the string remains unchanged.
Examples of strip() Function in Python
Example 1: Using strip() Without Parameters
python
str1 = ” Welcome to Software Moji Moji! “
after_strip = str1.strip()
print(after_strip)
Output:
css
Welcome to Software Moji Moji!
Explanation: Since no parameter is specified, the strip() method removes the leading and trailing whitespace.
Example 2: Using strip() with Character Parameters
python
str1 = “****Welcome to Software Moji Moji!****”
after_strip = str1.strip(“*”)
print(after_strip)
Output:
css
Welcome to Software Moji Moji!
Explanation: The strip(“*”) method removes all ‘*’ characters from the start and end of the string.
Example 3: strip() with Partial Character Removal
python
str2 = “Welcome to Software Moji Moji!”
after_strip1 = str2.strip(” Moji!”)
print(after_strip1)
Output:
css
Welcome to Software Moji
Explanation: Only the specified characters ” Moji!” are removed if they match the start or end of the string.
Example 4: strip() with Non-string Data Types
python
mylist = [“a”, “b”, “c”]
print(mylist.strip())
Output:
pgsql
AttributeError: ‘list’ object has no attribute ‘strip’
Explanation: The strip() method works only with string data types. Using it on other types like lists or tuples will result in an error.
Why Use Python strip()?
- To clean data by removing unnecessary spaces or symbols.
- To ensure consistent string formatting before data validation or storage.
- Useful in file handling, text parsing, and data scraping scenarios.
Key Takeaways:
✅ The strip() method removes characters from the start and end of a string.
✅ If no character parameter is given, it defaults to trimming whitespace.
✅ Works only with string data types.
✅ If no matching characters are found, the string is returned unchanged.