I don't quite get this "string".find()
Steven Bethard
steven.bethard at gmail.com
Thu Nov 11 15:37:26 EST 2004
Caleb Hattingh <caleb1 <at> telkomsa.net> writes:
>
> I don't know why the function was set up this way. However, an empty
> string can be found in an infinite number of places within any other
> string.
Infinite might be an exaggeration. Since there are only a finite number of
indices into a string (len(s) + 1), there are only a finite number of places an
empty sting may be found in any given string:
>>> s = 'abc'
>>> s.find('')
0
>>> s.find('', 1)
1
>>> s.find('', 2)
2
>>> s.find('', 3)
3
>>> s.find('', 4)
-1
You can't, say, find the empty string somewhere between indices 1 and 2.
> Also, if you want to check whether a string is empty, I do
>
> >>> "test" == ""
> False
An empty string evaluates to False in a boolean context, so you probably don't
usually want to actually test like this. A couple of options:
>>> s = ''
>>> bool(s)
False
>>> s = ''
>>> if s:
... print 'not empty'
... else:
... print 'empty'
...
empty
My suspicion is that any time you actually test against an empty string, you're
probably doing this in the context of an if statement or a while loop, so you
can simply use the string directly instead of testing anything.
Steve
More information about the Python-list
mailing list