Python strip()

Learn how Python strip() works with examples. Remove leading and trailing whitespace, strip specific characters, compare strip(), lstrip(), and rstrip(), and avoid common mistakes with prefixes and suffixes.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Python strip()

The strip() method removes leading and trailing whitespace from a string by default. You can also pass a chars argument to remove selected characters from both ends. It never removes characters from the middle of the string.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Quick answer: trim whitespace in Python

Use text.strip() to remove whitespace from both ends. Use text.lstrip() for the left side and text.rstrip() for the right side.

python
text = "  hello world  "

print(text.strip())
print(text.lstrip())
print(text.rstrip())
Output

The first line prints hello world with no edge spaces. The second keeps trailing spaces. The third keeps leading spaces.


Python strip() quick reference

Task Use
Remove whitespace from both ends text.strip()
Remove whitespace from left side text.lstrip()
Remove whitespace from right side text.rstrip()
Remove newline at end line.rstrip("\n")
Remove spaces and tabs text.strip()
Remove selected characters from both ends text.strip(".,!")
Remove selected characters from left side text.lstrip("0")
Remove selected characters from right side text.rstrip("/")
Remove exact prefix text.removeprefix(prefix)
Remove exact suffix text.removesuffix(suffix)
Remove all spaces, including middle text.replace(" ", "")
Normalize repeated whitespace " ".join(text.split())

What does strip() do in Python?

strip() returns a new string with leading and trailing characters removed. By default it removes whitespace: spaces, tabs, newlines, and other Unicode whitespace. It does not modify the original string because strings are immutable.

python
original = "  data  "
cleaned = original.strip()

print(original)
print(cleaned)
print(original is cleaned)
Output

You should see data unchanged, data as the trimmed result, and False because strip() creates a new string object. Characters in the middle of the string are never touched.


Python strip() syntax

Syntax: string.strip(chars=None)

  • chars is optional.
  • If chars is omitted or None, Python removes whitespace from both ends.
  • If chars is provided, Python removes any character in that set from both ends, repeatedly, until it reaches a character not in the set.

Important: chars is a set of characters, not an exact prefix or suffix string. The Python documentation states this explicitly and recommends removeprefix() and removesuffix() when you need exact prefix or suffix removal.


Remove whitespace from a string using strip()

Use text.strip() to clean user input, file lines, form values, and CSV-like fields.

python
user = "  bashir alam  "
print(f"|{user.strip()}|")
Output

The output shows |bashir alam| with no leading or trailing spaces. Internal spaces between words stay in place.


Remove whitespace from left or right side

Use lstrip() for leading whitespace and rstrip() for trailing whitespace.

Method Removes from
strip() Both beginning and end
lstrip() Beginning only
rstrip() End only
python
text = "   bashir alam    "

print(f"|{text.lstrip()}|")
print(f"|{text.rstrip()}|")
Output

The first result keeps trailing spaces. The second keeps leading spaces.


strip() vs lstrip() vs rstrip()

Use strip() when both sides should be cleaned. Use lstrip() when only the left side matters, such as removing leading zeros or a leading symbol. Use rstrip() when only the right side matters, such as trailing slashes or newline characters. When comparing cleaned values, pair stripping with Python compare strings techniques.


Remove newline from the end of a string

When you read lines from a file, each line often ends with \n. Use rstrip("\n") to remove only that newline.

python
line = "first line\n"
wide = "  text  \n"

print(repr(line.rstrip("\n")))
print(repr(wide.strip()))
print(repr(wide.rstrip("\n")))
Output

line.rstrip("\n") returns 'first line'. wide.strip() also removes the leading and trailing spaces. wide.rstrip("\n") keeps the spaces but drops the newline.

For Windows-style endings, use line.rstrip("\r\n").


Strip specific characters from a string

Pass a string of characters to strip(chars). Python treats it as a set and removes matching characters from both ends until it hits a character outside that set.

python
token = "!!!hello!!!"
print(token.strip("!."))
Output

The result is hello. Python removed every ! from both edges. It did not look for an exact substring.


strip() does not remove exact prefixes or suffixes

This is the most important rule to remember. strip("abc") removes any combination of a, b, and c from the edges. It does not remove only the exact word "abc".

python
word = "abcfoobarabc"

print(word.strip("abc"))
print("abcfoobar".removeprefix("abc"))
print("abcfoobar".removesuffix("abc"))
Output

strip("abc") returns foobar because Python peeled off individual a, b, and c characters from both ends. That is different from removing the exact prefix "abc" once.

Do not use lstrip("prefix") or rstrip(".txt") when you mean exact prefix or suffix removal.


Remove exact prefix with removeprefix()

Use text.removeprefix(prefix) when the prefix must match exactly once at the start. Available in Python 3.9+.

python
name = "prefix_value"
print(name.removeprefix("prefix_"))
Output

The result is value. If the prefix is not present, the original string is returned unchanged.


Remove exact suffix with removesuffix()

Use text.removesuffix(suffix) for exact suffix removal. Available in Python 3.9+.

python
filename = "report.txt"
print(filename.removesuffix(".txt"))
Output

The result is report. This is the safe way to drop a file extension from the end of a name.


Remove all spaces from a string

strip() only removes leading and trailing whitespace. It does not collapse or delete spaces in the middle.

python
messy = "  too   many  spaces  "

print(messy.replace(" ", ""))
print(" ".join(messy.split()))
Output

replace(" ", "") removes every normal space, including those in the middle. " ".join(messy.split()) keeps one space between words and trims edge whitespace—a common concatenation pattern after splitting. For more splitting patterns, see Python split string.


Strip punctuation or special characters

Use strip(".,!?") to remove punctuation from both edges only. Punctuation in the middle stays.

python
label = "...,hello!?..."
print(label.strip(".,!?"))
Output

The result is hello. The commas and exclamation marks inside the word are not removed.


Strip digits or zero padding

Use lstrip("0") to remove leading zeros from numeric strings.

python
code = "0001200"

print(code.lstrip("0"))
print(code.strip("0"))
Output

lstrip("0") returns 1200. strip("0") returns 12 because trailing zeros are also removed. Be careful when zeros are meaningful, such as in IDs or formatted codes.


Strip file paths, URLs, or slashes

Use rstrip("/") to remove a trailing slash from a URL or path.

python
url = "https://example.com/api/"
path = "/api/v1/"
filename = "report.txt"

print(url.rstrip("/"))
print(path.strip("/"))
print(filename.strip(".txt"))
print(filename.removesuffix(".txt"))
Output

rstrip("/") and strip("/") work on individual slash characters, not on full path segments. strip(".txt") is a common bug: it removes any mix of ., t, and x from both ends, so "report.txt" becomes repor. Use removesuffix(".txt") or pathlib for file extensions.


Summary

Use strip() to remove leading and trailing whitespace. Use lstrip() for the left side and rstrip() for the right side. The chars argument removes a set of characters from the edges, not an exact substring. For exact prefix or suffix removal, use removeprefix() and removesuffix(). For all spaces or normalized spacing, use replace() or split() with join().


References


Frequently Asked Questions

1. What does strip() do in Python?

strip() returns a new string with leading and trailing whitespace removed by default. It does not change the original string or remove characters from the middle.

2. Does strip("abc") remove the exact string "abc"?

No. The chars argument is a set of characters. strip("abc") removes any combination of a, b, and c from both ends, not the exact substring "abc".

3. What is the difference between strip(), lstrip(), and rstrip()?

strip() removes from both ends. lstrip() removes from the left only. rstrip() removes from the right only.

4. How do you remove an exact prefix or suffix in Python?

Use removeprefix() and removesuffix() in Python 3.9+. They remove an exact prefix or suffix string once, which strip() and lstrip() do not do.

5. How do you remove all spaces from a string?

strip() only removes leading and trailing whitespace. Use replace(" ", "") to delete every space, or " ".join(text.split()) to normalize spaces between words.

6. How do you remove a newline from the end of a line?

Use line.rstrip("\n") when reading file lines. Use rstrip("\r\n") for Windows-style line endings.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …