移除字串左側(開頭)特定字元是資料清洗、路徑處理、輸入正規化的常見需求。Python lstrip() 方法回傳新字串,移除開頭連續出現的指定字元集合中的字元,預設移除空白字元。本文詳細說明語法、行為細節、常見誤區與實戰模式。
str.lstrip([chars])
chars 是字元集合,非前綴字串。"abc".lstrip("ab") 移除 'a' 和 'b',非移除 "ab" 子字串。#!/usr/bin/python3
# 範例 1:預設移除空白
s1 = " hello world "
print(repr(s1.lstrip())) # 'hello world '(右側空白保留)
# 範例 2:移除指定字元
s2 = "88888888this is string example....wow!!!8888888"
print(s2.lstrip('8')) # this is string example....wow!!!8888888
# 範例 3:字元集合行為(非前綴匹配)
s3 = "abacus"
print(s3.lstrip("abc")) # 'us'(移除 a、b、a、c,遇到 u 停止)
s4 = "xyxxyhello"
print(s4.lstrip("xy")) # 'hello'(移除所有 x、y)
# 範例 4:順序無關、重複無關
print("cba".lstrip("abc")) # ''(全移除)
print("abc".lstrip("cba")) # ''(同樣全移除)
# 範例 5:空字串與無匹配
print("hello".lstrip("xyz")) # 'hello'(無匹配字元)
print("".lstrip("abc")) # ''
# 範例 6:Unicode 空白
s5 = "\t\n \u3000 測試"
print(repr(s5.lstrip())) # '測試'(含全形空格 U+3000)
# 錯誤預期:移除 "https://"
url = "https://example.com"
print(url.lstrip("https://")) # 'example.com'(巧合正確)
# 實際行為:移除 h、t、t、p、:、/、/ 字元
url2 = "https://example.com"
print(url2.lstrip("https://")) # 's://example.com'(s 不在集合中,殘留)
# 正確移除前綴:Python 3.9+ removeprefix()
print(url2.removeprefix("https://")) # 'example.com'
# 相容寫法
if url2.startswith("https://"):
url2 = url2[len("https://"):]
# 想移除前導零
num = "000123"
print(num.lstrip("0")) # '123' 正確
# 但若字串含其他字元
code = "00A001"
print(code.lstrip("0")) # 'A001'(A 停止,後續 0 保留)
paths = ["/home/user", "//var//log", "///etc"]
normalized = [p.lstrip("/") for p in paths]
print(normalized) # ['home/user', 'var//log', 'etc']
def normalize_number(s):
# 移除前導零,但保留至少一個字元
stripped = s.lstrip('0')
return stripped if stripped else '0'
print(normalize_number("000123")) # '123'
print(normalize_number("0000")) # '0'
print(normalize_number("123")) # '123'
lines = [
"### 標題",
"## 子標題",
"# 項目",
" 縮排文字"
]
cleaned = [line.lstrip("# ") for line in lines]
print(cleaned) # ['標題', '子標題', '項目', '縮排文字']
def trim(s, chars=None):
return s.lstrip(chars).rstrip(chars)
print(repr(trim(" hello "))) # 'hello'
print(repr(trim("xyhelloxy", "xy"))) # 'hello'
| 方法 | 方向 | 參數 | 行為 |
|---|---|---|---|
| lstrip() | 左側 | 字元集合 | 移除開頭連續匹配字元 |
| rstrip() | 右側 | 字元集合 | 移除結尾連續匹配字元 |
| strip() | 兩側 | 字元集合 | 移除首尾連續匹配字元 |
| removeprefix() | 左側 | 前綴字串 | 完全匹配前綴才移除(3.9+) |
| removesuffix() | 右側 | 後綴字串 | 完全匹配後綴才移除(3.9+) |
import re
# 移除開頭的數字與底線
def lstrip_digits_underscore(s):
return re.sub(r'^[\d_]+', '', s)
print(lstrip_digits_underscore("123_abc")) # 'abc'
print(lstrip_digits_underscore("__init__")) # 'init__'
# 移除開頭的特定模式(如日期)
def lstrip_pattern(s, pattern):
m = re.match(pattern, s)
return s[m.end():] if m else s
print(lstrip_pattern("2024-01-15 Log entry", r'\d{4}-\d{2}-\d{2}\s*')) # 'Log entry'
lstrip() 是移除字串左側字元的標準方法,**參數為字元集合而非前綴字串**是核心概念。若需移除固定前綴,Python 3.9+ 請用 removeprefix(),舊版用 startswith() 切片。搭配 rstrip()、strip() 可處理各種修剪需求。理解「字元集合、連續匹配、遇不匹配停止」三原則,能避免 90% 的誤用情況。