str.strip()

Removes whitespace (or given characters) from the start and end of a string.

Returns
A new string without the characters at the edges.
Changes the original
No
On this page

Example

#
Python
raw = "   Emma Smith \n"
print(f"[{raw.strip()}]")
print(f"[{raw.lstrip()}]".replace("\n", "\\n"))
print("...Wow!!!".strip(".!"))
print("lesson_01.py".removesuffix(".py"))
Resultsaved result, you can check it
[Emma Smith]
[Emma Smith \n]
Wow
lesson_01

Definition and usage

#

The strip() method returns the string without spaces, tabs, and newline characters at the start and end. Whitespace in the middle stays untouched.

With an argument, it removes a given set of characters, not a specific substring: strip(".!") removes every period and exclamation mark from both ends, in any order.

The lstrip() and rstrip() variants work only on the left or right side. To remove a specific prefix or suffix, use removeprefix() and removesuffix().

Syntax

#
Syntax
string.strip()
string.strip(chars)

Parameters

#
  • chars

    str, optional

    The set of characters to remove. Defaults to whitespace.

Good practices

#
  • Always run text typed by a user through strip() before saving or comparing it.
  • Remember that the strip() argument is a set of characters. To remove a whole word, use removeprefix() or removesuffix().

Related entries

#

Spotted a mistake or missing an example? Write to us.