str.strip()
The .strip() method removes leading and trailing characters from a string. By default, it removes all whitespace characters—spaces, tabs, newlines, carriage returns, and form feeds. This makes it essential for cleaning user input, processing file contents, and parsing data from external sources.
Signature
str.strip([chars])
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
chars | str | None | A string specifying the set of characters to remove. If None, all whitespace characters are removed. |
Return Value
Returns a new string with the specified characters removed from both the beginning and end. The original string remains unchanged since strings are immutable in Python.
Examples
Basic Usage
>>> " hello ".strip()
'hello'
>>> "\t\nhello\n\t".strip()
'hello'
>>> " \n\n multiple\nlines \n".strip()
'multiple\nlines'
The default behavior handles common whitespace scenarios. It removes spaces at the start and end, along with any newline or tab characters.
Stripping Specific Characters
>>> "xxhelloxx".strip('x')
'hello'
>>> "---hello---".strip('-')
'hello'
>>> "xyxyhelloxyxy".strip('xy')
'hello'
>>> "***hello***".strip('*')
'hello'
>>> "<<<>>>data<<<>>>".strip('<>')
'data'
When you provide the chars argument, .strip() removes any combination of those characters from both ends. It keeps stripping until it encounters a character not in the set.
Stripping Multiple Character Types
>>> "##!!@@data@@!!##".strip('#!@')
'data'
>>> " \t-=--hello--=-\t ".strip(' \t-=')
'hello'
This is useful when dealing with formatted strings that have consistent prefixes or suffixes.
Practical Use Cases
Cleaning user input:
username = input("Enter username: ").strip()
email = input("Enter email: ").strip()
# Without strip(), users might accidentally add spaces
# that cause login failures or inconsistent data
Reading file lines:
with open("data.txt") as f:
for line in f:
line = line.strip()
if line: # Skip empty lines
process(line)
# Note: file.readlines() keeps the newline character
# strip() removes it for clean processing
Parsing CSV or delimited data:
>>> " 42 ".strip()
'42'
>>> " 3.14 ".strip()
'3.14'
>>> "\tpassword\t".strip()
'password'
Handling API responses:
response = api.get("/user")
name = response.json()["name"].strip() # Clean any accidental whitespace
Behavior Details
How It Works
The method scans from the beginning of the string, removing characters that appear in the chars set. Once it hits a character not in the set, it stops. Then it repeats the process from the end of the string.
>>> "aaabaaaa".strip('a')
'ba' # Leading 'a's removed, stops at 'b'
# Trailing 'a's removed, stops at 'a'
>>> "aaabbaaaa".strip('a')
'bb' # Leading 'a's removed, stops at 'b'
# Trailing 'a's removed, stops at 'b'
Character Order Doesn’t Matter
>>> "hello---".strip('-')
'hello'
>>> "hello---".strip('---')
'hello'
>>> "hello---".strip('--')
'hello'
# All equivalent when removing the same characters
Empty String Returns Empty
>>> "".strip()
''
>>> " ".strip()
''
Performance
.strip() is implemented in C and runs in O(n) time where n is the number of characters removed. For most use cases involving short strings or whitespace removal, the performance is negligible. The method creates a new string, so memory usage scales with the input size.
Common Mistakes
Assuming it removes from the middle of the string:
>>> "hello world".strip()
'hello world' # Space in middle is NOT removed
# For middle spaces, use replace():
>>> "hello world".replace(" ", "")
'helloworld'
Forgetting it returns a new string:
s = " hello "
s.strip() # This returns a new string but doesn't modify s
s = s.strip() # Assign the result to keep it
Confusing with JavaScript’s trim():
# Python: strip() is the equivalent of JavaScript's trim()
# Both remove leading/trailing whitespace