'<char> in <string>' works, why doesnt '<string> in <string>'?
Sheila King
usenet at thinkspot.net
Sat Mar 9 14:38:33 EST 2002
On 9 Mar 2002 08:40:50 -0800, morton at dennisinter.com (damien morton) wrote
in comp.lang.python in article
<4abd9ce7.0203090840.21a020eb at posting.google.com>:
> Its counter-intuitive for someone playing with strings as strings
> rather than as sequences of characters, however.
>
> 'c' in 'the quick brown fox' -> 1
>
> 'fox' in 'the quick brown fox' -> 1 (instead of TypeError)
>
> Is there any circumstance where youd expect (or want) the later not to
> work? I expected and wanted it to work (but instead got an error), its
> quite a clear and unambiguous expression (for strings only).
Suppose
word = 'fox'
container = 'the quick brown fox'
What if the type of container is not necessarily known. i.e. it is possible
that container could be something like:
container = ['the', 'quick', 'brown', 'fox']
And suppose the type were important in this case, as to whether it were a
single string vs. a list of words. As it is now, you are able to make this
distinction, whereas with what you propose that distinction would be lost.
I can't come up right now with a practical example of why this would be
important or useful, though.
Anyhow, if you have a string, as shown above, and you want to test for a
word in the string (rather than using the .find method for strings) you
could do this:
word in string.split(container)
this would split the string container on any and all white spaces into just
the word elements.
--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/
More information about the Python-list
mailing list