Skip to content

Module 7 · Strings — topic 11 of 22

strip()

strip(), lstrip() and rstrip() remove unwanted characters, usually whitespace, from the ends of a string. Learn how the optional characters argument works and why strip() is essential for input.

Beginner 10 min read·Lesson 92 of 306 in Python Programming

Learning objectives

  • Remove whitespace from one or both ends
  • Strip specific characters with an argument
  • Avoid the misconception that strip removes substrings

Definition

strip(), lstrip() and rstrip() remove unwanted characters, usually whitespace, from the ends of a string. Learn how the optional characters argument works and why strip() is essential for input.

Introduction

strip() returns a copy of a string with leading and trailing whitespace removed: spaces, tabs and newlines. lstrip() removes from the left only, rstrip() from the right only. Characters in the middle are never touched.

Why it matters

Invisible spaces cause real bugs: "Pune " is not equal to "Pune", and a line read from a file ends with \n. Calling strip() on input and file lines is one of the most useful habits in text processing.

Detailed explanation

Whitespace includes more than the space bar: tabs, newlines, carriage returns and some special Unicode spaces copied from web pages or PDFs. strip() with no argument removes all of them, which is why it is safer than strip(" ") for cleaning input.

With no argument, all whitespace characters at the ends are removed, including spaces, \t and \n.

With an argument, strip(chars) removes any of the given characters from the ends: "*Sale*".strip("*") is "Sale". The argument is a set of characters, not a word to remove.

Because of that, "www.example.com".strip("w.com") gives "example": it removes w, ., c, o and m from both ends wherever they appear. To remove an exact prefix or suffix, use removeprefix() and removesuffix().

rstrip("\n") removes just the newline from a line read from a file, keeping other trailing spaces if they matter.

strip() returns a new string; assign the result.

An all-whitespace string becomes "" after strip(), which makes empty-input checks reliable: if not text.strip():.

Syntax

Python
clean = text.strip()
left_clean = text.lstrip()
right_clean = text.rstrip("\n")
trimmed = text.strip("*-")
  • No argument removes whitespace.
  • lstrip/rstrip work on one side only.
  • An argument lists characters to remove, in any order.

Code examples

Whitespace at the ends

Python
raw = " \t Pune \n"
print(repr(raw.strip()))
print(repr(raw.lstrip()))
print(repr(raw.rstrip()))
Output
'Pune'
'Pune \n'
'  \t Pune'

Specific characters

Python
print("***Sale***".strip("*"))
print("--==Title==--".strip("-="))
print(" a b ".strip())
Output
Sale
Title
a  b

More examples

Cleaning lines and the character-set trap

Python
lines = ["Asha, 82 \n", " Ben,67\n", "\n", " Chen , 91"]
for line in lines:
if not line.strip():
continue
name, mark = line.split(",")
print(f"{name.strip()}: {int(mark.strip())}")
site = "www.example.com"
print(site.strip("w.com"))
print(site.removeprefix("www.").removesuffix(".com"))
Output
Asha: 82
Ben: 67
Chen: 91
example
example

Step-by-step explanation

  • if not line.strip() skips lines that contain only whitespace.
  • Each part from split(",") is stripped separately, removing spaces around names and marks.
  • int() of a stripped mark converts it safely.
  • strip("w.com") happens to give example here, but only because it removes those characters individually; removeprefix/removesuffix remove the exact text and are the safe choice.

Expected output

Running “Cleaning lines and the character-set trap” prints exactly:

TextOutput
Asha: 82
Ben: 67
Chen: 91
example
example

Practical applications

  • Form handlers strip every text field before validating it.
  • File readers rstrip("\n") each line.
  • Data cleaning removes stray currency symbols with strip("₹ ").

Best practices

  • Strip all user input and file lines.
  • Use removeprefix/removesuffix for exact text.
  • Use rstrip("\n") when other trailing spaces matter.

Common mistakes

Expecting strip to remove a word

Avoid

"report.txt".strip(".txt") # "repor"

Prefer

"report.txt".removesuffix(".txt")

strip removes any of the characters ., t and x from the ends, eating the final t of report.

Expecting strip to remove inner spaces

Avoid

"a b".strip() # still "a b"

Prefer

" ".join("a b".split())

strip only affects the ends; split and join collapse inner spaces.

Key takeaways

  • strip() removes whitespace from both ends; lstrip/rstrip from one end.
  • An argument is a set of characters, not a substring.
  • Use removeprefix()/removesuffix() for exact affixes.

Try it yourself

  1. 1
    Remove leading zeros from "000452" with lstrip and convert it to an int.
  2. 2
    Clean the string "--Python--" to "Python" with strip.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic