String method

str.lstrip()

Removes whitespace, or any characters you list, from the start (left side) of a string. The right side stays as it is.

BeginnerEvery example below runs in your browser. Change the code and press Run.

str.lstrip(chars=None)

lstrip() works like str.strip() but only on the left: it removes spaces, tabs and new lines from the start of a string and leaves the end alone. The "l" stands for left.

It is handy for indented text, for leading zeros in codes such as "000123", and for marks like # or > at the start of a line.

Like strip(), its argument is a set of characters, not a word. url.lstrip("https://") removes every h, t, p, s, colon and slash it finds at the start, which can eat letters of the address itself. Use str.removeprefix() to remove an exact beginning.

Parameters

ParameterWhat it is
chars
optional, default None
The characters to remove from the start, as one string. Order does not matter. With None, whitespace is removed.

Return value

A new string without those characters at the start.

Examples

1Remove indentation

Pythoneditable
line = "    total = 10"
print(f"[{line.lstrip()}]")
Output
[total = 10]

2Remove leading zeros

Pythoneditable
code = "000123"
print(code.lstrip("0"))
print(repr("000".lstrip("0")))
Output
123
''

If the string is all zeros, nothing is left. int(code) is often the better choice when you want the number.

3Remove comment marks at the start of a line

Pythoneditable
lines = ["# Settings", "## Colours", "size = 3"]
for line in lines:
    print(line.lstrip("# "))
Output
Settings
Colours
size = 3

4Only the left side changes

Pythoneditable
text = "  hello  "
print(f"[{text.lstrip()}]")
print(f"[{text.rstrip()}]")
print(f"[{text.strip()}]")
Output
[hello  ]
[  hello]
[hello]

Common mistakes

Using lstrip() to remove a prefix

The argument is a set of characters. "https://shop.example.com".lstrip("https://") also removes the s and h of shop, because those letters are in the set. removeprefix() removes the exact text once.

Pythoneditable
url = "https://shop.example.com"
print(url.lstrip("https://"))
print(url.removeprefix("https://"))
Output
op.example.com
shop.example.com

Questions people ask

What is the difference between lstrip() and removeprefix()?

lstrip("ab") removes any number of a and b characters from the start. removeprefix("ab") removes the text "ab" exactly once, and only if the string starts with it.

How do I remove leading zeros but keep a single 0?

Use code.lstrip("0") or "0": when lstrip() leaves an empty string, the or gives "0" instead.

Does lstrip() change the original string?

No. Strings cannot change; store the result: text = text.lstrip().

Spotted a mistake on this page? Tell us