Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.lstrip() method

Reference for Python str.lstrip(): remove leading whitespace or a set of characters from the start of a string, and why it is not the same as removing a prefix.

The lstrip() method returns a copy of the string with characters removed from the left (start) side. With no argument it removes whitespace. With an argument it removes any of the characters listed there, repeatedly, until it meets a character that is not in the list.

It is the left-hand half of strip(). Only the start of the string is touched; the right side is left as it is.

Python
print("   hello  ".lstrip() + "|")   # hello  |

Try it

Python Removing leading whitespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python The argument is a set of characters, not a prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.lstrip(chars=None)
Name Description
chars Optional. A string whose characters are all removed from the start, in any order and any number of times. If omitted or None, whitespace is removed.

Return value: a new string with the leading characters removed. If nothing matches, the result equals the original.

Raises: TypeError if chars is not a string or None.

Usage notes

  • A set of characters. "abc".lstrip("ba") removes the leading b and a and gives "c". It does not look for the text "ba". For an exact prefix, use removeprefix() (Python 3.9+).
  • Stops at the first non-matching character. Characters in the middle or the end are never touched.
  • Whitespace by default. The default set is everything isspace() accepts: spaces, tabs, newlines and Unicode spaces.
  • Returns a new string. The original is unchanged, so assign the result.
  • Strip digits or zeros. "007".lstrip("0") gives "7", but "000" becomes "". Handle that case if you need a number: int("000") is safer.
  • Use for indentation. line.lstrip() is a quick way to drop indentation, and len(line) - len(line.lstrip()) measures it.
  • Bytes have bytes.lstrip(), which takes bytes as the argument.