廢話不多說,上正文。
對比
Python 3.9 的新特性中,有兩個新的字符串方法:str.removeprefix(prefix, /)
、str.removesuffix(suffix, /)
,前者是去除前綴,後者是去除後綴。
ěi~,是不是感覺似曾相識,這不就是 lstrip()
、rstrip()
的功能嗎?還真不是。
來看一個對比:
>>> '今天天氣不錯'.removeprefix('今天')
'天氣不錯'
>>> '今天天氣不錯'.lstrip('今天')
'氣不錯'
🤔是不是挺奇怪,我估計可能坑了很多人。下面來看下爲什麼 lstrip()
會出現這樣的結果。
Why
首先需要說明的是,lstrip([chars])
這樣的行爲,是一個 feature,不是一個 bug。
看下文檔是怎麼說的:
Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. The chars argument is not a prefix; rather, all combinations of its values are stripped:
也就是說,其參數 chars
雖然是一個字符串,但不是直接去除字串形式的 chars
,而是在從左到右遍歷原字符串,去除在 chars
中的字符,直到遇到第一個不在 cahrs
中的字符爲止,即類似如下實現:
def lstrip(s, chars):
chars = set(chars)
for i in s:
if i in chars:
s = s.replace(i, '')
else:
break
return s
>>> lstrip('今天天氣不錯', '今天')
'氣不錯'
有時候可能這並不是我們想要的情況(可能大多數情況都不是),我們想要的是可能是下面這樣的效果:
def lstrip(s, chars):
if s.startswith(chars):
return s[len(chars):]
return s
>>> lstrip('今天天氣不錯', '今天天氣')
'天氣不錯'
而 Python 3.9,就直接內置了這個方法,命名爲 removeprefix()
,後面如果我們想要去除前綴而不是前綴所包括的那些字符的時候,就可以直接用了:
>>> '今天天氣不錯'.removeprefix('今天')
'天氣不錯'
Reference
- PEP 616 – String methods to remove prefixes and suffixes | Python.org
- Built-in Types — Python 3.9.0b1 documentation
- Mailman 3 [Python-ideas] Re: New explicit methods to trim strings - Python-ideas - python.org
- issue 39880: string.lstrip() with leading '3’s - Python tracker
- Understanding python’s lstrip method on strings - Stack Overflow
- New Features in Python 3.9 You Should Know About - Martin Heinz
- Python Release Python 3.9.0b1 | Python.org