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'} 的前導字元。
paths = ['/home/user', '//var/log', '///tmp']
clean = [p.lstrip('/') for p in paths]
print(clean) # ['home/user', 'var/log', 'tmp']
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'
log_line = '*** ERROR: Disk full'
msg = log_line.lstrip('* ')
print(msg) # 'ERROR: Disk full'
rstrip 實作 stripdef my_strip(s, chars=None):
return s.lstrip(chars).rstrip(chars)
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。
chars 固定,可預編譯正則 re.compile(f'^[{re.escape(chars)}]+') 替代,但 lstrip 通常已足夠快。| 方法 | 方向 | 參數語意 |
|---|---|---|
lstrip([chars]) | 左/開頭 | 字元集合 |
rstrip([chars]) | 右/結尾 | 字元集合 |
strip([chars]) | 兩端 | 字元集合 |
removeprefix(prefix) | 左/開頭 | 完整前綴字串 (Py3.9+) |
removesuffix(suffix) | 右/結尾 | 完整後綴字串 (Py3.9+) |