CodeBlanks Logo Icon CodeBlanks

strip, lstrip, rstrip

Learn to remove edge whitespace with strip.

strip, lstrip, rstrip

strip removes characters from both ends of a string. The default is whitespace:

"  hello  ".strip()    # "hello"
"--hello--".strip("-")  # "hello"

lstrip removes from the left, rstrip from the right. These methods are commonly used to clean up user input.

strip does not modify the original string; it returns a new one. Strings are immutable in Python, so this rule applies to all string methods.

lstrip vs rstrip

lstrip removes only from the left, rstrip only from the right:

"  hello  ".lstrip()  # "hello  "
"  hello  ".rstrip()  # "  hello"

This is useful when only one side needs cleaning. For example, rstrip is preferred to remove trailing spaces from a line.

All three methods return a new string; they do not change the original.

Practice Clean with strip

Assign " hello " to raw. Assign raw.strip() to clean. Then print print(clean).

Starter code

main.py
# Clean with strip

Sample solution

main.py
raw = "  hello  "
clean = raw.strip()
print(clean)

Expected output

hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the strip call

Question
clean = "  hello  ".____()
Answer
clean = "  hello  ".strip()

Explanation: strip() removes leading and trailing spaces.

2 Match the strip methods

Term Meaning
strip Both sides
lstrip Left side
rstrip Right side
new string Return value

3 What does "--hi--".strip("-") return?

  • "--hi--"
  • "--hi"
  • "hi" Correct answer
  • "hi--"

Explanation: strip removes '-' from both ends.

All lessons in Beginner