Python doesn’t have a trim() function; str.strip() is the trim. Called with no argument, the strip function returns a new string with the leading and trailing whitespace removed. Pass a string of characters, and it removes those from both ends instead:
" Emily Carter \n".strip() # 'Emily Carter'
"$1,299.00".strip("$") # '1,299.00'
The original string never changes, so you always keep the returned value.
In this tutorial, I’ll show you how the Python strip function handles every kind of whitespace, how lstrip() and rstrip() trim one side, and why strip(".txt") can eat letters you wanted.
All output comes from Python 3.12.5 with pandas 3.0.6, using messy customer records like the ones a US sign-up form collects.
Python strip() syntax and parameters
The signature is str.strip([chars]). It takes one optional argument and always returns a new string:
charsomitted orNone: removes whitespace from both ends.charsgiven: removes any mix of those characters from both ends, stopping at the first character that isn’t in the set.- Characters in the middle of the string are never touched.
Here’s the simplest case, a customer name with stray spaces and a newline from a pasted form field:
raw_name = " Emily Carter \n"
clean = raw_name.strip()
print(repr(raw_name))
print(repr(clean))
print(len(raw_name), "->", len(clean))
Output:
' Emily Carter \n'
'Emily Carter'
18 -> 12
The 18-character original came back as a 12-character clean name, and repr() makes the removed spaces and \n visible.
If you need to drop a character from anywhere, not just the ends, use the approaches in removing a character from a string in Python.
What whitespace does strip() remove?
Without an argument, strip() removes every character that str.isspace() calls whitespace. That’s more than the space bar:
samples = {
"spaces": " Austin ",
"tab + newline": "\tAustin\n",
"Windows CRLF": "Austin\r\n",
"non-breaking": "\xa0Austin\xa0",
"zero-width": "\u200bAustin\u200b",
}
for label, s in samples.items():
print(f"{label:<14} {s.strip()!r}")
zw = samples["zero-width"]
print("fixed: ", repr(zw.strip().strip("\u200b\ufeff")))
Output:
spaces 'Austin'
tab + newline 'Austin'
Windows CRLF 'Austin'
non-breaking 'Austin'
zero-width '\u200bAustin\u200b'
fixed: 'Austin'

\r\n and the non-breaking space all go; the zero-width space survives until you name it.The non-breaking space (\xa0) is common in text copied from web pages, and strip() handles it. The zero-width space (\u200b) isn’t whitespace to Python, so it stays until you pass it in chars.
Line breaks in the middle of the text need a different tool; see removing newlines from a string in Python.
Trim one side with lstrip() and rstrip()
lstrip() trims only the left (leading) end and rstrip() only the right (trailing) end. Both take the same optional chars argument:
line = " ORD-1042, 89.99 \n"
print(repr(line.lstrip())) # left side only
print(repr(line.rstrip())) # right side only
print(repr(line.rstrip("\n"))) # just the newline
Output:
'ORD-1042, 89.99 \n'
' ORD-1042, 89.99'
' ORD-1042, 89.99 '
rstrip("\n") is the careful choice when you read lines from a file: it removes the newline but keeps intentional trailing spaces in fixed-width data.
I use it in almost every loop that goes through a file; reading a file line by line in Python shows that pattern end to end.
Strip specific characters from a string
Pass the characters you want gone. Python treats the argument as a set and keeps removing from each end while the next character is in it:
print("$1,299.00".strip("$"))
print("**SALE**".strip("*"))
print("---Denver---".strip("-"))
print(" $42.10 ".strip(" $")) # spaces AND dollar signs
# chars is a SET of characters, not a word:
print("www.example.com".strip("w.com"))
print("receipt.txt".strip(".txt")) # eats the last t of receipt
Output:
1,299.00
SALE
Denver
42.10
example
receip

strip(" $") removes spaces and dollar signs together, but strip(".txt") turns receipt.txt into receip.The last two lines are the trap. "w.com" isn’t a word to strip(); it’s the letters w, o, c, m and a dot, so www. and .com both disappear.
With receipt.txt, the trailing t of receipt is also in the set, so it goes too. Order inside chars doesn’t matter either.
Once the dollar sign is gone, you can turn the price into a number; converting a string to a float in Python covers the comma and error handling.
Why does strip() remove extra letters? Use removeprefix() and removesuffix()
When you mean an exact prefix or suffix, use str.removeprefix() or str.removesuffix() (Python 3.9+). They remove the whole string once, or do nothing if it doesn’t match:
file_name = "receipt.txt"
print("strip: ", file_name.strip(".txt"))
print("removesuffix: ", file_name.removesuffix(".txt"))
sku = "SKU-STOCK-17"
print("lstrip: ", sku.lstrip("SKU-"))
print("removeprefix: ", sku.removeprefix("SKU-"))
print("no match: ", sku.removeprefix("ID-"))
Output:
strip: receip
removesuffix: receipt
lstrip: TOCK-17
removeprefix: STOCK-17
no match: SKU-STOCK-17

lstrip("SKU-") also eats the S of STOCK, while removeprefix("SKU-") stops after the exact prefix.removesuffix(".txt") keeps receipt intact, and removeprefix("ID-") returns the SKU unchanged because it didn’t start with that text.
For lists of prefixes and older Python versions, see removing prefixes from strings in Python.
Does strip() change the original string?
No. Strings are immutable, so strip() builds a new string. Calling it without saving the result is the most common strip bug I see in code reviews:
email = " Megan.Bowen@Example.com \n"
email.strip() # result thrown away
print(repr(email))
email = email.strip().lower() # reassign the new string
print(repr(email))
answer = " YES \n"
print(answer == "yes", answer.strip().lower() == "yes")
Output:
' Megan.Bowen@Example.com \n'
'megan.bowen@example.com'
False True
The first print() still shows the spaces and newline. After reassigning, the email is clean and lowercase, and the chained strip().lower() makes the yes/no check pass.
The reason strings work this way is covered in mutable vs immutable in Python, and chaining with case changes is in converting a string to lowercase in Python.
Strip every item in a list
Comma-separated text almost always comes with spaces around each value. Split first, then strip each piece:
row = " James Miller , Austin ,TX, 78701 , $89.50 "
fields = [f.strip() for f in row.split(",")]
print(fields)
tags = [" python ", "\tdata\n", " ", "web "]
print(list(map(str.strip, tags)))
print([t.strip() for t in tags if t.strip()]) # drop blanks
Output:
['James Miller', 'Austin', 'TX', '78701', '$89.50']
['python', 'data', '', 'web']
['python', 'data', 'web']
The row became five clean fields. map(str.strip, tags) does the same as the comprehension, and the if t.strip() filter drops the item that was only spaces.
If list comprehensions are new to you, start with list comprehension in Python; splitting on commas is covered in splitting a string by comma in Python.
Trim strings in a pandas DataFrame with str.strip()
pandas has its own vectorized version, Series.str.strip(), with the same lstrip/rstrip variants and chars argument. Same customer data, now as a DataFrame:
import pandas as pd
df = pd.DataFrame({
"name": [" Emily Carter", "James Miller ", " Olivia Brown "],
"state": [" TX", "CO ", " NY "],
"total": [" $89.50", "$1,299.00 ", " $42.10 "],
})
print("TX rows before:", (df["state"] == "TX").sum())
df = df.apply(lambda col: col.str.strip())
df["total"] = df["total"].str.lstrip("$").str.replace(",", "")
df["total"] = df["total"].astype(float)
print("TX rows after: ", (df["state"] == "TX").sum())
print(df.to_string(float_format="{:.2f}".format))
print(f"Sum: ${df['total'].sum():,.2f}")
Output:
TX rows before: 0
TX rows after: 1
name state total
0 Emily Carter TX 89.50
1 James Miller CO 1299.00
2 Olivia Brown NY 42.10
Sum: $1,430.60

str.strip() one does, and the totals sum to $1,430.60.That filter result is why trimming matters: " TX" and "TX" are different values, so the count went from 0 to 1 only after stripping.
df.apply(lambda col: col.str.strip()) works here because every column is text. With mixed columns, apply it to the text columns only.
Remove whitespace inside a string, not just the ends
strip() stops at the first non-whitespace character, so spaces between words stay. Pick the tool by what you want to keep:
city = " New York City "
print(repr(city.strip())) # ends only
print(repr(" ".join(city.split()))) # ends + inner runs
print(repr(city.replace(" ", ""))) # every space
Output:
'New York City'
'New York City'
'NewYorkCity'
" ".join(city.split()) trims the ends and collapses inner runs to one space. More options are in replacing multiple spaces with a single space in Python and removing all spaces from a string in Python.
strip(), lstrip(), rstrip() and removeprefix() compared
| Method | Removes from | Argument means | Example result |
|---|---|---|---|
strip() | Both ends | Set of characters | ' $42.10 '.strip(' $') → '42.10' |
lstrip() | Left end | Set of characters | ' ORD-1042'.lstrip() → 'ORD-1042' |
rstrip() | Right end | Set of characters | 'line\n'.rstrip('\n') → 'line' |
removeprefix() | Left end, once | Exact text | 'SKU-STOCK-17' → 'STOCK-17' |
removesuffix() | Right end, once | Exact text | 'receipt.txt' → 'receipt' |
Series.str.strip() | Both ends | Set of characters | pandas columns |
For more string clean-up, try one of these next:
- Split a string by whitespace in Python
- Replace whitespaces with underscore in Python
- Remove the first and last character from a string in Python
- Remove non-ASCII characters in Python
Frequently asked questions
Does Python have a trim() function?
No. Python trims strings with strip() (both ends), lstrip() (left) and rstrip() (right).
What does strip() do with no arguments?
It returns a copy without leading and trailing whitespace: spaces, tabs, newlines, carriage returns and other characters where isspace() is true.
What is the difference between strip(), lstrip() and rstrip()?
strip() trims both ends, lstrip() only the start and rstrip() only the end. All three accept the same optional characters argument.
Does strip() remove spaces in the middle of a string?
No. Use " ".join(s.split()) to collapse inner spaces or s.replace(" ", "") to remove all of them.
Why did strip(“.txt”) remove a letter from my file name?
The argument is a set of characters, not a suffix. Use name.removesuffix(".txt") to remove the exact text.
Where is str.strip() documented?
See str.strip() in the official Python docs.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn