我在Python的str.endswith()里找到了一个bug吗?

2024-04-16 19:07:32 发布

您现在位置:Python中文网/ 问答频道 /正文

根据Python documentation

str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. Withoptional end, stop comparing at that position.

Changed in version 2.5: Accept tuples as suffix.

下面的代码应该返回True,但是在Python 2.7.3中它返回False

"hello-".endswith(('.', ',', ':', ';', '-' '?', '!'))

似乎str.endswith()忽略了第四个元组元素之外的任何内容:

^{pr2}$

我有没有发现一个虫子,或者我遗漏了什么?在


Tags: thefalsetruestringreturnifthatdocumentation
3条回答

如果你把元组写成

>>> tuple_example = ('.', ',', ':', '-', ';' '?', '!')

然后元组将变成

^{pr2}$

所以这就是为什么返回False

已经指出,相邻的字符串文本是连接在一起的,但是我想添加一些额外的信息和上下文。在

这是一个与C共享(并借用)C的特性

另外,它不像'+'这样的串联运算符,并且在没有任何额外开销的情况下,将它们视为在源代码中直接连接在一起一样。在

例如:

>>> 'a' 'b' * 2
'abab'

这是一个有用的特性还是一个令人讨厌的设计,这实际上是一个意见问题,但它确实允许通过将文本封装在圆括号中来分解多行之间的字符串文本。在

^{pr2}$

这种用法(以及与#defines一起使用)是它最初在C中有用的原因,后来在Python中出现。在

or am I missing something?

元组中的';'后面缺少逗号:

>>> "hello;".endswith(('.', ',', ':', '-', ';' '?', '!'))
                                         #    ^
                                         # comma missing
False

因此,;和{}被连接起来。因此,对于这种情况,以;?结尾的字符串将返回True

^{pr2}$

添加逗号后,它将按预期工作:

>>> "hello;".endswith(('.', ',', ':', '-', ';', '?', '!'))
True

相关问题 更多 >