首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 字串去除空白完全指南:strip/lstrip/rstrip 參數、Unicode 空白字元與自訂字元集實戰

     編輯:更多程式設計知識

str.strip([chars]) 系列是字串邊界清理的核心工具。預設移除 Unicode 空白字元,支援自訂字元集移除特定前綴/後綴。

三大方法對照

方法移除位置語法
strip()兩端s.strip([chars])
lstrip()左端 (開頭)s.lstrip([chars])
rstrip()右端 (結尾)s.rstrip([chars])

預設行為:Unicode 空白字元


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 字元。

自訂字元集:chars 參數詳解


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'

實戰場景

1. 清理使用者輸入


def clean_input(s):
    return s.strip().replace('\u3000', ' ')  # 全形空格轉半形

2. 移除特定前綴/後綴 (Python 3.9+ 推薦 removeprefix/removesuffix)


# 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

3. 解析固定格式行


line = '  001  Apple  30  '
fields = line.strip().split()  # ['001', 'Apple', '30']
# 或指定分隔符
'001|Apple|30'.strip().split('|')

4. 清理檔案讀取的換行


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% 的字串邊界清理需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved