萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python lstrip() 方法詳解:移除字串前導字元

方法簽名

str.lstrip([chars]) -> str

行為定義

回傳字串副本,移除 開頭 連續出現的、屬於 chars 集合的字元。chars 為字元集合 (非子字串),預設為所有 Unicode 空白字元 (isspace() 為 True)。

基本範例

>> '   hello'.lstrip()
'hello'
>>> '\t\n  hello'.lstrip()
'hello'
>>> 'xxxyhello'.lstrip('xy')
'hello'
>>> 'xyxhello'.lstrip('xy')
'hello'   # 只要是 x 或 y 就移除,不考慮順序
>>> 'hello'.lstrip('h')
'ello'
>>> 'hello'.lstrip('x')
'hello'   # 開頭非 x,不移除

關鍵特性:字元集合而非前綴字串

>> 'abcde'.lstrip('abc')
'de'      # 移除 a, b, c 三種字元,直到遇到 d
>>> 'abcde'.lstrip('abz')
'cde'     # z 不在字串開頭,不影響
>>> 'abcde'.removeprefix('abc')  # Python 3.9+ 真正移除前綴
'de'

重要:lstrip('abc') ≠ 移除前綴 'abc',而是移除所有屬於 {'a','b','c'} 的前導字元。

實際應用場景

1. 清理檔案路徑前導分隔符

paths = ['/home/user', '//var/log', '///tmp']
clean = [p.lstrip('/') for p in paths]
print(clean)  # ['home/user', 'var/log', 'tmp']

2. 解析固定寬度欄位 (COBOL 風格)

record = '00012345  John Doe      '
# 欄位 1: 8 碼數字 (前導零)
# 欄位 2: 20 碼姓名 (前導空白)
id_str = record[:8].lstrip('0') or '0'
name = record[8:28].lstrip()
print(id_str, name)  # '12345' 'John Doe'

3. 移除特定標記字元

log_line = '*** ERROR: Disk full'
msg = log_line.lstrip('* ')
print(msg)  # 'ERROR: Disk full'

4. 配合 rstrip 實作 strip

def my_strip(s, chars=None):
    return s.lstrip(chars).rstrip(chars)

Python 3.9+ 新方法:removeprefix() / removesuffix()

>> 'TestFile.txt'.removeprefix('Test')
'File.txt'
>>> 'TestFile.txt'.lstrip('Test')
'File.txt'   # 偶然正確,但語意不同
>>> 'TestTestFile.txt'.lstrip('Test')
'File.txt'   # 移除所有 T,e,s,t
>>> 'TestTestFile.txt'.removeprefix('Test')
'TestFile.txt'  # 僅移除一次前綴

需要精確移除前綴/後綴時,請使用 removeprefix/removesuffix。

效能提示

  • C 層實作,單趟掃描直到遇到不在集合的字元。
  • 大量資料清洗時,若 chars 固定,可預編譯正則 re.compile(f'^[{re.escape(chars)}]+') 替代,但 lstrip 通常已足夠快。

相關方法對照

方法方向參數語意
lstrip([chars])左/開頭字元集合
rstrip([chars])右/結尾字元集合
strip([chars])兩端字元集合
removeprefix(prefix)左/開頭完整前綴字串 (Py3.9+)
removesuffix(suffix)右/結尾完整後綴字串 (Py3.9+)
copyright © 萬盛學電腦網 all rights reserved