str.strip([chars]) 系列是字串邊界清理的核心工具。預設移除 Unicode 空白字元,支援自訂字元集移除特定前綴/後綴。
| 方法 | 移除位置 | 語法 |
|---|---|---|
strip() | 兩端 | s.strip([chars]) |
lstrip() | 左端 (開頭) | s.lstrip([chars]) |
rstrip() | 右端 (結尾) | s.rstrip([chars]) |
s = ' Hi, Jack! \t\n'
print(repr(s.strip())) # 'Hi, Jack!'
print(repr(s.lstrip())) # 'Hi, Jack! \t\n'
print(repr(s.rstrip())) # ' Hi, Jack!'
涵蓋:空格、\t\n\r\v\f、全形空格 \u3000、零寬空格 \u200b 等所有 Unicode White_Space 字元。
s = 'xyxyHello xyxy'
print(s.strip('xy')) # 'Hello ' (移除兩端所有 x/y)
print(s.lstrip('xy')) # 'Hello xyxy'
print(s.rstrip('xy')) # 'xyxyHello '
# 重要:chars 是「字元集合」,非「子字串」
s = 'abcXYZ'
print(s.strip('ac')) # 'bXY' (移除 a 和 c,保留 b X Y)
print(s.strip('abc')) # 'XYZ'
def clean_input(s):
return s.strip().replace('\u3000', ' ') # 全形空格轉半形
# Python 3.9+
'prefix_content'.removeprefix('prefix_') # 'content'
'content_suffix'.removesuffix('_suffix') # 'content'
# 相容寫法
def remove_prefix(s, prefix):
return s[len(prefix):] if s.startswith(prefix) else s
line = ' 001 Apple 30 '
fields = line.strip().split() # ['001', 'Apple', '30']
# 或指定分隔符
'001|Apple|30'.strip().split('|')
with open('data.txt') as f:
lines = [line.rstrip('\n') for line in f] # 只移除 \n,保留尾部空格
# 或
lines = [line.rstrip() for line in f] # 移除所有尾部空白
strip 為 C 層實現,極快map(str.strip, lines) 或列表推導式re.sub(r'\s+', ' ', s)
# 誤以為移除子字串
'hello world'.strip('lo') # 'he world' (移除 h/e/l/o 字元)
# 正確移除子字串
'hello world'.removeprefix('hello ') # 'world' (Py3.9+)
善用 strip 系列配合 split/removeprefix,能輕鬆處理 90% 的字串邊界清理需求。