Start learning free

LESSON 68 OF 344 · STRINGS I

String Strip in Python: strip(), lstrip() and rstrip()

Lesson Read the full explanation

In Python, you can remove leading and trailing whitespace from a string using strip():

s.strip()   # removes leading and trailing whitespace
s.lstrip()  # removes only leading (left) whitespace
s.rstrip()  # removes only trailing (right) whitespace

Here are some examples:

s = "  hello  "
print(s.strip())   # "hello"
print(s.lstrip())  # "hello  "
print(s.rstrip())  # "  hello"

strip() returns a new string — the original is not modified.


Assignment
Follow the Coding Tutorial and strip whitespace from s!


Hint
Use s.strip() and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · STRINGS I

    String Strip in Python, explained

    What strip() does

    Text from users, files and web forms often arrives with extra whitespace around it: spaces typed by accident, a tab, or the newline at the end of a line. The strip() method removes that whitespace from both ends of a string and returns the cleaned result. It is also called trimming in other languages.

    s = "  hello  "
    print(repr(s.strip()))   # 'hello'
    print(repr(s.lstrip()))  # 'hello  '
    print(repr(s.rstrip()))  # '  hello'
    print(repr(s))           # '  hello  '
    

    The examples use repr() so that the quotes show exactly where each string begins and ends. Without it, trailing spaces are invisible when printed.

    The three methods

    • strip() removes whitespace at the start and at the end.
    • lstrip() removes it only at the start, the left side.
    • rstrip() removes it only at the end, the right side.

    Whitespace here means more than the space character. Tabs and newlines count too:

    print(repr("\t hi\n".strip()))  # 'hi'
    print(repr("   ".strip()))       # ''
    

    A string made only of whitespace becomes the empty string.

    Only the ends are touched

    Whitespace in the middle of the text is never removed. " a b ".strip() gives 'a b', with both inner spaces still in place. If you need to remove inner spaces too, use replace(" ", ""), or split the text into words with split() and join them again.

    Stripping other characters

    You can pass a string of characters to strip instead of whitespace. Python then removes any of those characters from the ends, in any order, until it meets one that is not in the set:

    print("xxhixx".strip("x"))      # hi
    print("--a--".lstrip("-"))       # a--
    print("hello".strip("lho"))      # e
    

    The last line shows the thing that surprises people: the argument is a set of characters, not a word to cut off. Here h, l and o are all removed from the ends, leaving e. To remove a specific prefix or suffix, use removeprefix() and removesuffix(), for example "file.txt".removesuffix(".txt") gives "file".

    Where stripping helps in practice

    Stripping is usually the first step of cleaning input, before the text is compared or split. A typed answer with stray spaces and a newline still matches once it is cleaned, and a comma separated line gives tidy items when each piece is stripped:

    answer = "  YES \n"
    print(answer.strip().lower() == "yes")  # True
    
    line = "apple, banana ,cherry"
    print([item.strip() for item in line.split(",")])  # ['apple', 'banana', 'cherry']
    

    In the first example the calls are chained: strip() returns a string, and that string has its own lower() method. Each step receives the result of the one before it.

    Immutability and common mistakes

    Strings are immutable, so strip() cannot change the string it is called on. It returns a new one. This leads to the most frequent mistake:

    t = "  x "
    t.strip()
    print(repr(t))  # '  x '
    
    t = t.strip()
    print(repr(t))  # 'x'
    

    The first t.strip() produced a cleaned string that nobody kept. Only the assignment on the next line stores it.

    • Comparing before cleaning. " Ann \n" == "Ann" is False, while " Ann \n".strip() == "Ann" is True. Strip input before you compare it.
    • Expecting inner whitespace to go. Only leading and trailing whitespace is removed.
    • Using strip() to delete a word. The argument is a set of characters. Use replace() or removesuffix() for text.
    • Forgetting the parentheses. s.strip without them is the method object itself, not the cleaned string.

    The exercise, step by step

    The lesson gives s set to " hello ", which has two spaces on each side, and asks for the text without them.

    1. Pick the method. Whitespace has to go from both sides, so strip() is the right one. The one-sided versions would leave spaces behind.
    2. Call it on s. No argument is needed, because whitespace is the default.
    3. Keep the result. Assign it to a new variable named result below the existing line.
    s = "  hello  "
    
    result = s.strip()
    

    Now result is "hello", five characters long, while s still has all nine of its original characters. You can confirm this with len(s) and len(result), which give 9 and 5.

    Key takeaways

    • strip() removes whitespace from both ends, lstrip() from the left and rstrip() from the right.
    • Spaces, tabs and newlines all count as whitespace, and whitespace inside the text stays.
    • A string argument names a set of characters to strip, not a piece of text.
    • The original string never changes, so always store the returned value.
    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free