Python String strip()
Method
The strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters from a string. By default, it removes whitespace characters like spaces, tabs, and newlines.
Syntax
string.strip([chars])
Parameters:
chars
(optional) – A string specifying the set of characters to remove. If not provided, whitespace is removed.
Returns:
- A new string with leading and trailing characters removed.
Example 1: Remove Leading and Trailing Spaces
text = " Hello World! "
cleaned = text.strip()
print(cleaned)
Hello World!
Example 2: Remove Custom Characters
text = "---Python---"
cleaned = text.strip("-")
print(cleaned)
Python
Example 3: Remove Multiple Characters
text = "xyxyLearn Pythonxy"
result = text.strip("xy")
print(result)
Learn Python
Why? The method removed all leading and trailing x
and y
characters.
Use Case: Clean User Input
username = input("Enter your name: ")
username = username.strip()
print("Welcome,", username)
This ensures that any accidental spaces entered by the user are removed.
Difference between strip()
, lstrip()
, and rstrip()
strip()
: removes from both endslstrip()
: removes from the left onlyrstrip()
: removes from the right only
Common Mistakes
- Forgetting that
strip()
does not change the original string (strings are immutable) - Thinking it removes characters *within* the string — it only affects the ends.
Interview Tip
strip()
is often used in input validation, file reading, and web scraping to clean messy strings.
Summary
strip()
removes leading and trailing characters- Default: removes whitespace
- Can remove custom characters by passing a string to
strip()
- Returns a new string (original string is unchanged)
Practice Problem
Write a program to remove leading and trailing @
and #
symbols from a string:
raw = "@@@#Python is fun##@@@"
clean = raw.strip("@#")
print(clean)
Expected Output:
Python is fun