bool Retu-6ren">
gpt4 book ai didi

python - 为什么 str.endswith 不允许 "suffix"参数是一个列表?

转载 作者:太空狗 更新时间:2023-10-30 02:11:36 27 4
gpt4 key购买 nike

我看到 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) 语法,它们也只接受元组。

参见 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.

代码没有理由不支持任意的非字符串迭代(产生字符串)。您可以在 Python issue tracker 中提交功能请求为此,如果您对此有强烈的感觉。但是,知道 Guido van Rossum 已经 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).

关于python - 为什么 str.endswith 不允许 "suffix"参数是一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21352537/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com