Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 lstrip() Method

Python3 lstrip() Method

Python3 Strings Python3 Strings


Description

The lstrip() method removes spaces or specified characters from the left side of a string.

Syntax

Syntax of the lstrip() method:


str.lstrip([chars])

Parameters

**chars (optional):** specifies the set of characters to remove (as a string).

If omitted or None, whitespace characters are removed by default (spaces, tabs, newlines, carriage returns, vertical tabs and form feeds).

**Note:** chars is a set of characters, not a complete prefix. The method removes all characters that appear in chars from the left side until it encounters a character not in the set.

Return Value

Returns a new string (the original string is not modified).

Key characteristics

Acts on the left side only: does not affect characters on the right side or in the middle of the string.

Character set matching: chars is a set of characters, not a complete prefix. For example:


"abc123".lstrip("ab")  # 移除 'a' 和 'b' → "c123"

Whitespace range: includes spaces, tab characters, newline characters, etc.

Comparison with other methods

Method Direction of action Example
lstrip() Remove characters on the left " hi ".lstrip() → "hi "
rstrip() Remove characters on the right " hi ".rstrip() → " hi"
strip() Remove characters on both sides " hi ".strip() → "hi"

Example

The following example shows how to use lstrip():

** 1. Remove leading whitespace characters**

text = "   Hello, World!   "
result = text.lstrip()
print(result)  # 输出: "Hello, World!   "(右侧空格保留)

2. Remove specified characters on the left

text = "www.example.com"
result = text.lstrip("wcmo.")  # 移除左侧出现的任意字符:w, c, m, o, .
print(result)  # 输出: "example.com"(左侧的 "www." 被移除)

3. The order of the character set does not matter

text = "123abc"
result = text.lstrip("321")  # 移除左侧的 '1', '2', '3'(顺序不影响)
print(result)  # 输出: "abc"

4. Stop when a character not in the set is encountered

text = "123abc"
result = text.lstrip("12")  # 只移除左侧的 '1' 和 '2',遇到 '3' 停止
print(result)  # 输出: "3abc"

5. The original string is unchanged

text = "   Hello"
result = text.lstrip()
print(text)   # 输出: "   Hello"(原字符串未修改)
print(result) # 输出: "Hello"

Python3 Strings Python3 Strings