去除字符串首尾的空白字符 (空格、製表符、換行符) 或指定字符集,是數據清洗、輸入驗證、文本解析的高頻操作。Python 提供 strip/lstrip/rstrip 三大方法,本文全面解析其參數行為、Unicode 支援、效能與陷阱。
| 方法 | 方向 | 語法 | 說明 |
|---|---|---|---|
strip() | 雙端 | s.strip([chars]) | 移除首尾指定字符集 |
lstrip() | 左端 (開頭) | s.lstrip([chars]) | 移除開頭指定字符集 |
rstrip() | 右端 (結尾) | s.rstrip([chars]) | 移除結尾指定字符集 |
# 默認:移除所有 Unicode 空白字符 (空格、\t、\n、\r、\v、\f 等)
s = ' \t\nHello\r\n '
s.strip() # 'Hello'
s.lstrip() # 'Hello\r\n '
s.rstrip() # ' \t\nHello'
# 指定字符集:移除首尾「屬於該集合」的字符,而非「子字符串」
s = 'xyxHelloxyx'
s.strip('xy') # 'Hello' (移除所有首尾的 x 或 y)
s.strip('xyx') # 'Hello' (同效果,集合去重)
# 不是前綴/後綴匹配!
s = 'abcHelloabc'
s.strip('abc') # 'Hello' (正確)
s.strip('ab') # 'cHelloabc' (只移除 a/b,c 保留)
strip('abc') == strip('cba')
# 所有 Unicode 空白字符 (Zs, Zl, Zp, Cc 中部分)
import unicodedata
spaces = ''.join(chr(i) for i in range(0x110000)
if unicodedata.category(chr(i)).startswith('Z'))
# 包含:\u0020(空格) \u00A0(不換行空格) \u1680(Ogham空格)
# \u2000-\u200A(各種寬度空格) \u2028(行分隔) \u2029(段分隔)
# \u3000(全形空格) 等
s = '\u3000\u2003Hello\u2002\u00A0'
s.strip() # 'Hello' (自動識別所有 Unicode 空白)
# 精確移除前綴/後綴 (非字符集)
s = 'prefix_content_suffix'
s.removeprefix('prefix_') # 'content_suffix'
s.removesuffix('_suffix') # 'prefix_content'
# 不匹配時返回原字符串 (不報錯)
s.removeprefix('other_') # 'prefix_content_suffix'
import timeit
s = ' hello '
timeit.timeit('s.strip()', globals=globals()) # ~55ns
timeit.timeit('s.lstrip()', globals=globals()) # ~50ns
timeit.timeit('s.rstrip()', globals=globals()) # ~50ns
timeit.timeit('s.strip(" ")', globals=globals()) # ~65ns (字符集解析開銷)
def clean_input(raw):
return raw.strip() # 移除首尾空白、換行
username = clean_input(input("用戶名: "))
line = ' key = "value" '
key, val = line.split('=', 1)
key = key.strip()
val = val.strip().strip('"\'') # 移除首尾引號
path = ' /home/user/file.txt \n'
path = path.strip() # '/home/user/file.txt'
# 移除首尾的 *、#、-
comment = '*** Important Notice ***'
clean = comment.strip('*#- ') # 'Important Notice'
'a b'.strip() == 'a b'strip() 不會移除 '.'、',' 等標點b' abc '.strip() == b'abc'strip() (雙端)、lstrip() (左)、rstrip() (右)strip('chars') 理解為「字符集合」而非子串removeprefix/removesuffix熟練掌握去空白工具箱,能讓數據清洗代碼更簡潔、更健壯、更符合國際化要求。