萬盛學電腦網

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

Python 字串 strip() 方法:移除首尾指定字符(預設空白)

方法簽名


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 參數是字符集合,非子字串。

copyright © 萬盛學電腦網 all rights reserved