Python strip() 去除空白

strip() 方法用來移除字串開頭和結尾的空白字元。

基本用法

text = "   Hello World   "
result = text.strip()
print(f"'{result}'")  # 'Hello World'

語法

str.strip(chars=None)
  • chars:要移除的字元集合,預設為 None(空白字元)

strip()、lstrip()、rstrip()

text = "   Hello World   "

# strip() - 移除兩端
print(f"'{text.strip()}'")   # 'Hello World'

# lstrip() - 只移除左邊(開頭)
print(f"'{text.lstrip()}'")  # 'Hello World   '

# rstrip() - 只移除右邊(結尾)
print(f"'{text.rstrip()}'")  # '   Hello World'

移除的空白字元

預設會移除以下空白字元:

  • 空格
  • 換行 \n
  • 歸位 \r
  • Tab \t
  • 垂直 Tab \v
  • 換頁 \f
text = " \t\n Hello World \n\t "
result = text.strip()
print(f"'{result}'")  # 'Hello World'

指定要移除的字元

text = "###Hello World###"
result = text.strip("#")
print(result)  # Hello World

text = "xxxHello Worldxxx"
result = text.strip("x")
print(result)  # Hello World

移除多種字元

指定的是字元集合,不是子字串:

text = "##**Hello World**##"
result = text.strip("#*")
print(result)  # Hello World

# 注意:會移除 # 或 * 的任何組合
text = "*#*#Hello World#*#*"
result = text.strip("#*")
print(result)  # Hello World

移除特定字元

# 移除引號
text = '"Hello World"'
result = text.strip('"')
print(result)  # Hello World

# 移除括號
text = "(Hello World)"
result = text.strip("()")
print(result)  # Hello World

# 移除數字
text = "123Hello World321"
result = text.strip("0123456789")
print(result)  # Hello World

不會移除中間的空白

strip() 只移除開頭和結尾,不會影響中間的空白:

text = "   Hello   World   "
result = text.strip()
print(f"'{result}'")  # 'Hello   World'

# 如果要移除中間的多餘空白,使用 split() 和 join()
result = " ".join(text.split())
print(f"'{result}'")  # 'Hello World'

實際範例

清理使用者輸入

user_input = "   alice@example.com   "
email = user_input.strip()
print(email)  # alice@example.com

處理檔案每一行

lines = """
    Line 1
    Line 2
    Line 3
"""

for line in lines.strip().split("\n"):
    print(f"'{line.strip()}'")

輸出:

'Line 1'
'Line 2'
'Line 3'

移除 BOM

# UTF-8 BOM
text = "\ufeffHello World"
result = text.lstrip("\ufeff")
print(result)  # Hello World

清理 CSV 資料

csv_line = "  Alice  ,  25  ,  Taipei  "
fields = [field.strip() for field in csv_line.split(",")]
print(fields)  # ['Alice', '25', 'Taipei']

移除 URL 的斜線

url = "/users/profile/"
clean_url = url.strip("/")
print(clean_url)  # users/profile

移除註解符號

comment = "# This is a comment"
text = comment.lstrip("# ")
print(text)  # This is a comment

removeprefix() 和 removesuffix()

Python 3.9+ 提供移除特定前綴或後綴的方法:

# removeprefix() - 移除前綴
text = "HelloWorld"
print(text.removeprefix("Hello"))  # World
print(text.removeprefix("Hi"))     # HelloWorld(沒有此前綴,不變)

# removesuffix() - 移除後綴
text = "HelloWorld"
print(text.removesuffix("World"))  # Hello
print(text.removesuffix("Earth"))  # HelloWorld(沒有此後綴,不變)

這和 strip() 不同,removeprefix()removesuffix() 是移除特定的子字串,而不是字元集合:

text = "HelloWorld"

# strip 會移除所有匹配的字元
print(text.strip("Helo"))  # World(移除了 H, e, l, o)

# removeprefix 只移除完整的前綴
print(text.removeprefix("Helo"))  # HelloWorld(沒有 Helo 前綴)
print(text.removeprefix("Hello")) # World