我看到str.endswith
方法允许suffix
参数去是一个字符串的元组:
Docstring:
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
所以我猜测它也接受字符串或其他一些iterables的名单,但是当我试过了,路过一个列表会引发错误:
In [300]: s='aaa'
In [301]: s.endswith(('a', 'b'))
Out[301]: True
In [302]: s.endswith(['a', 'b'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-302-d70816089fed> in <module>()
----> 1 s.endswith(['a', 'b'])
TypeError: endswith first arg must be str, unicode, or tuple, not list
那么,为什么只接受字符串的元组?
该API只是呼应isinstance()
和except (Exception1, Exception2)
语法,这两者只接受元组为好。
以同样的方式,异常可以有指定类型的元组和isinstance可以采取的类型,str.startswith和的endsWith元组可以采取可能的前缀/后缀的元组。
没有理由的代码不能支持任意的,非字符串iterables(产生字符串)。如果你感到强烈的这个你可以在文件的Python issue tracker该功能请求。然而,知道吉多·范罗苏姆已经stated that they are not interested in changing this:
总之,我希望你能放弃你推动这项功能。它只是似乎并不那么重要,你真的只是移动不一致,以不同的地方(国家有专项套管柱,而不是元组)。
也许str.startswith
和str.endswith
只接受tuples
和不接受的,因为历史原因lists
:isinstance
工作方式相同,自2001年12月21日(这一天的Python 2.2发布)。
下面是来自startswith / ENDWITH feature request的摘录:
以同样的方式,异常可以有指定类型的元组和isinstance可以采取的类型,str.startswith和的endsWith元组可以采取可能的前缀/后缀的元组。