str.strip([chars]) -> str
返回新字串,移除首尾處於 chars 集合中的字符。chars 缺省為所有空白字符(空格、\t、\n、\r 等)。非前綴/後綴匹配,而是「字符集合去除」。
s = "0000000this is string example....wow!!!0000000"
print(s.strip('0')) # this is string example....wow!!!
# 預設去空白
" \t\n hello \n\t ".strip() # 'hello'
| 方法 | 方向 | 範例 |
|---|---|---|
strip(chars) | 雙端 | 'abc'.strip('ac') → 'b' |
lstrip(chars) | 左端 | 'abc'.lstrip('a') → 'bc' |
rstrip(chars) | 右端 | 'abc'.rstrip('c') → 'ab' |
removeprefix(pre) | 前綴精確 | 'abc'.removeprefix('ab') → 'c' (3.9+) |
removesuffix(suf) | 後綴精確 | 'abc'.removesuffix('bc') → 'a' (3.9+) |
strip('abc') vs removeprefix('abc')
'abcabc'.strip('abc') # '' 移除所有首尾 a/b/c
'abcabc'.removeprefix('abc') # 'abc' 僅移除完整前綴 'abc'
strip([chars]) 是「首尾字符集合去除」的標準工具。需精確前綴/後綴移除請用 3.9+ 新增的 removeprefix/removesuffix。記住:strip 參數是字符集合,非子字串。