Aaryan Dewan
Aaryan Dewan

Reputation: 204

Why do any of the ordered characters in a string appear to be a part of a list which is equivalent to that string?

My book says -

Strings and lists are actually similar, if you consider a string to be a “list” of single text characters.

Suppose that I have a string namely name=Zophie.

Now this string should have some resemblance with a list. So I type in another code that would tell me what should the items of that list be. The code goes like -

for i in name: print(‘* * * ‘ + i + ‘ * * *')

The output is:

* * * Z * * * * * * o * * * * * * p * * * * * * h * * * * * * i * * * * * * e * * *

This clearly shows that the list items of name are Z,o,p,h,i,e.

Now if I try to check wether the list has an item ’Zop' by using:

Zop in name

It returns True! That is, Python says that Zophie contains an item namely ’Zop’ but when I tried to list all the items using the for command, Zop didn’t show up.

What’s happening here?

Upvotes: 0

Views: 60

Answers (3)

Debosmit Ray
Debosmit Ray

Reputation: 5413

Looking at the section on Membership test detail, which is relevant to the in keyword. Paraphrasing from there,

For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

Although, I strongly suggest that elegant use of the re module can be picked over a membership test for a substring.

Upvotes: 0

Heiko Oberdiek
Heiko Oberdiek

Reputation: 1708

There are two different ins:

  • for i in name: The word in is part of the for-loop syntax. The statement iterates over the elements of the iterable name. If name is a string, then it iterates over the characters of the string.

  • 'Zop' in name: The word in is a comparison operator. From the documentation, 5.9.1 Membership test operations:

    For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

Upvotes: 2

lvc
lvc

Reputation: 35089

Any Python class is free to define various operations however it likes. Strings happen to implement the sequence protocol (meaning that iteration and [i] item access behave the same as lists), but also implement __contains__, which is responsible for x in y checks, to look for substrings rather than just single characters.

It is common for x in y membership testing to mean "x will appear if you print all the elements of y", but there's no rule saying that that has to be the case.

Upvotes: 2

Related Questions