[Tutor] Question about startswith() and endswith() in 2.5
Dick Moores
rdm at rcblue.com
Mon Sep 25 11:59:45 CEST 2006
http://www.python.org/doc/lib/string-methods.html has
=============================================
startswith( prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False.
prefix can also be a tuple of suffixes to look for. With optional
start, test string beginning at that position. With optional end,
stop comparing string at that position.
Changed in version 2.5: Accept tuples as prefix.
==============================================
and
================================================
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.
With optional start, test beginning at that position. With optional
end, stop comparing at that position.
Changed in version 2.5: Accept tuples as suffix.
==================================================
Through experimentation I now see a use for a tuple in which start
and end are indexes (as with the startswith() and endswith() of 2.4.3):
>>> s = "qwerty"
>>>
>>> s.startswith("er",2,3)
False
>>>
>>> s.startswith("er",2,4)
True
>>>
but
>>> 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?
Thanks,
Dick Moores
More information about the Tutor
mailing list