Python3 lstrip() Method
Description
The lstrip() method is used to truncate spaces or specified characters on the left side of a string.
Syntax
lstrip() method syntax:
str.lstrip([chars])
Parameters
chars (optional):Specifies a set of characters to be removed (in string form).
If omitted or None, whitespace characters are removed by default (space, \t, \n, \r, \v, \f).
Note:chars is a set of characters, not a complete prefix. The method removes all characters appearing 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 Features
Only affects the left side: 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 character range: includes space, tab (\t), newline (\n), etc.
Comparison with Other Methods
| Method | Direction | Example |
|---|---|---|
lstrip() |
Removes left-side characters | " hi ".lstrip() → "hi " |
rstrip() |
Removes right-side characters | " hi ".rstrip() → " hi" |
strip() |
Removes both-side characters | " hi ".strip() → "hi" |
Examples
The following examples demonstrate how to use lstrip():
1. Remove left-side whitespace characters
text = " Hello, World! " result = text.lstrip() print(result) # 输出: "Hello, World! "(右侧空格保留)
2. Remove specified characters from the left side
text = "www.example.com"
result = text.lstrip("wcmo.") # 移除左侧出现的任意字符:w, c, m, o, .
print(result) # 输出: "example.com"(左侧的 "www." 被移除)
3. Order of character set is irrelevant
text = "123abc"
result = text.lstrip("321") # 移除左侧的 '1', '2', '3'(顺序不影响)
print(result) # 输出: "abc"
4. Stops when encountering a character not in the set
text = "123abc"
result = text.lstrip("12") # 只移除左侧的 '1' 和 '2',遇到 '3' 停止
print(result) # 输出: "3abc"
5. The original string remains unchanged
text = " Hello" result = text.lstrip() print(text) # 输出: " Hello"(原字符串未修改) print(result) # 输出: "Hello"
Other Extensions
Python3 Strings