[Python-Dev] <int> in <str>

Zero Piraeus schesis at gmail.com
Tue Apr 3 19:53:48 EDT 2018


:

On 3 April 2018 at 20:34, Ethan Furman <ethan at stoneleaf.us> wrote:
> This behavior was recently brought to my attention [1]:
>
> --> 1 in 'hello'
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'in <string>' requires string as left operand, not int
>
> However, in any other collection (set, dict, list, tuple, etc), the answer
> would be False.
>
> Does anyone remember the reason why an exception is raised in the string
> instance instead of returning False?

The comparison doesn't seem to me to be valid: the 'in' operator for
all of those other collections tests whether an element is a member of
a collection, whereas for a string it tests whether a string is a
substring of another string.

In the first case, arbitrary objects can be members, but e.g.

    [2, 3, 4] in [1, 2, 3, 4, 5]

is False. In the second case, no non-string can ever be 'in' a string, but

    'bcd' in 'abcde'

is True. It's kinda-sorta like addition for numerics versus sequences;
they do different things.

 -[]z.


More information about the Python-Dev mailing list