萬盛學電腦網

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

Python rstrip() 方法詳解:移除字串尾部字元

方法簽名

str.rstrip([chars]) -> str

行為定義

回傳字串副本,移除 結尾 連續出現的、屬於 chars 集合的字元。chars 為字元集合 (非後綴字串),預設為所有 Unicode 空白字元。

基本範例

>> 'hello   '.rstrip()
'hello'
>>> 'hello\n\r\t'.rstrip()
'hello'
>>> 'hello...'.rstrip('.')
'hello'
>>> 'hello...'.rstrip('.!')
'hello'
>>> 'hello'.rstrip('o')
'hell'
>>> 'hello'.rstrip('x')
'hello'

關鍵特性:字元集合而非後綴字串

>> 'abcde'.rstrip('cde')
'ab'      # 移除 c,d,e 三種字元,直到遇到 b
>>> 'abcde'.removesuffix('cde')  # Python 3.9+ 真正移除後綴
'ab'

實際應用場景

1. 清理讀取行尾換行符

2. 移除 URL 尾部斜線

def normalize_url(url):
    return url.rstrip('/')

print(normalize_url('https://example.com/path/'))  # 'https://example.com/path'
print(normalize_url('https://example.com'))        # 'https://example.com'

3. 解析 CSV 行尾逗號

line = 'a,b,c,,,'
fields = line.rstrip(',').split(',')
print(fields)  # ['a', 'b', 'c'] (空欄位被移除)

4. 配合 lstrip 實作 strip

def my_strip(s, chars=None):
    return s.lstrip(chars).rstrip(chars)

Python 3.9+ 新方法:removesuffix()

>> 'TestFile.txt'.removesuffix('.txt')
'TestFile'
>>> 'TestFile.txt'.rstrip('.txt')
'TestFil'   # 移除 t, x, . 字元集合
>>> 'file.txt.txt'.removesuffix('.txt')
'file.txt'  # 僅移除一次

需要精確移除後綴時,請使用 removesuffix。

效能提示

  • C 層單趟從尾部掃描,極快。
  • 大量行處理時,列表推導 [line.rstrip() for line in f] 效能佳。

相關方法對照

方法方向參數語意Python 版本
lstrip([chars])左/開頭字元集合所有
rstrip([chars])右/結尾字元集合所有
strip([chars])兩端字元集合所有
removeprefix(prefix)左/開頭完整前綴字串3.9+
removesuffix(suffix)右/結尾完整後綴字串3.9+
copyright © 萬盛學電腦網 all rights reserved