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'
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'
line = 'a,b,c,,,'
fields = line.rstrip(',').split(',')
print(fields) # ['a', 'b', 'c'] (空欄位被移除)
lstrip 實作 stripdef my_strip(s, chars=None):
return s.lstrip(chars).rstrip(chars)
removesuffix()>> 'TestFile.txt'.removesuffix('.txt')
'TestFile'
>>> 'TestFile.txt'.rstrip('.txt')
'TestFil' # 移除 t, x, . 字元集合
>>> 'file.txt.txt'.removesuffix('.txt')
'file.txt' # 僅移除一次
需要精確移除後綴時,請使用 removesuffix。
[line.rstrip() for line in f] 效能佳。| 方法 | 方向 | 參數語意 | Python 版本 |
|---|---|---|---|
lstrip([chars]) | 左/開頭 | 字元集合 | 所有 |
rstrip([chars]) | 右/結尾 | 字元集合 | 所有 |
strip([chars]) | 兩端 | 字元集合 | 所有 |
removeprefix(prefix) | 左/開頭 | 完整前綴字串 | 3.9+ |
removesuffix(suffix) | 右/結尾 | 完整後綴字串 | 3.9+ |