Dick Moores wrote:
> >>> s.startswith("er","q","ty")
>
> Traceback (most recent call last):
> File "<pyshell#55>", line 1, in <module>
> s.startswith("er","q","ty")
> TypeError: slice indices must be integers or None or have an __index__ method
>
> On http://docs.python.org/whatsnew/other-lang.html I found
>
> ==================================================
> The startswith() and endswith() methods of string types now accept
> tuples of strings to check for.
>
>
> def is_image_file (filename):
> return filename.endswith(('.gif', '.jpg', '.tiff'))
>
> ====================================================
>
> This is the only example I've been able to find in the documentation
> that uses the new tuple of strings, and I don't understand it. The
> function is_image_file() will return filenames ending in '.gif', but
> what do '.jpg' (as start) and '.tiff' (as end) do? What kind of
> data(?) would this function be applied to? A Python list of filenames?
You're missing something. Do you see the doubled parentheses in the call
to endswith()? filename.endswith(('.gif', '.jpg', '.tiff')) is a call to
endswith() with a *single* argument, the tuple
('.gif', '.jpg', '.tiff'). The start and end arguments are omitted.
On the other hand, your call
s.startswith("er","q","ty")
is a call to startswith() with three arguments, the strings 'er', 'q'
and 'ty'.
To write is_image_file() prior to 2.5 you would have to write something
like this:
def is_image_file(filename):
for extn in ('.gif', '.jpg', '.tiff'):
if filename.endswith(extn):
return True
return False
Allowing the first argument to endswith() to be a tuple simplifies this
common usage.
Kent
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor