简体   繁体   中英

Why doesn't str.endswith allow the “suffix” parameter to be a list?

I see the str.endswith method allows the suffix param to be a tuple of strings :

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.

so I was guessing it also accepts a list of strings or some other iterables , but when I tried that, passing a list raises error:

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

So why it accepts only a tuple of strings ?

Probably str.startswith and str.endswith accept only tuples and don't accept lists because of the historical reasons: isinstance works the same way since December 21, 2001 (the day Python 2.2 was released).

Here's the excerpt from the startswith/endwith feature request :

In the same way that exceptions can have a tuple of types specified and isinstance can take a tuple of types, str.startswith and endswith could take a tuple of possible prefixes/suffixes.

The API simply echoes isinstance() and except (Exception1, Exception2) syntax, which both only accept tuples as well.

See the original feature request :

In the same way that exceptions can have a tuple of types specified and isinstance can take a tuple of types, str.startswith and endswith could take a tuple of possible prefixes/suffixes.

There is no reason the code couldn't support arbitrary, non-string iterables (yielding strings). You could file a feature request in the Python issue tracker for that if you feel strongly about this. However, know that Guido van Rossum has already stated that they are not interested in changing this :

All in all I hope you will give up your push for this feature. It just doesn't seem all that important, and you really just move the inconsistency to a different place (special-casing strings instead of tuples).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM