[Tutor] Question about startswith() and endswith() in 2.5

Andrei project5 at redrival.net
Mon Sep 25 13:50:26 CEST 2006


Dick Moores <rdm <at> rcblue.com> writes:
<snip>
> endswith( suffix[, start[, end]])
> Return True if the string ends with the specified suffix, otherwise 
> return False. suffix can also be a tuple of suffixes to look for. 
<snip>
>  >>> 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
<snip>
> def is_image_file (filename):
>      return filename.endswith(('.gif', '.jpg', '.tiff'))
<snip>
> 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?

Note that endswith(('.gif', '.jpg', '.tiff')) is a function call with ONE
parameter: the tuple ('.gif', '.jpg', '.tiff') - hence the double parentheses.
This parameter is the suffix. The optional start and end parameters are not
specified. You could read it like "if the filename ends with .gif or .jpg or
.tiff". In older Python versions, you could implement the same functionality as:

    if s.endswith('.gif') or s.endswith('.jpg') or s.endswith('.tiff')

This is in contrast with the example you give above, where
startswith("er","q","ty") is a function call with three separate parameters, all
of them strings. Since start ("q") and end ("ty") must be integers, this call
crashes.

Yours,

Andrei



More information about the Tutor mailing list