[Tutor] Multipart Question
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Thu May 8 17:14:02 2003
On Thu, 8 May 2003, Daniel Nash wrote:
> I came accross this bit of code:
>
> if contenttype[:10] == "multipart/":
> mimemsg = mimetools.Message(sys.__stdin__)
> boundary = mimemsg.getparam('boundary')
> .........
>
> What is the significance of the [:10]?
Hi Daniel,
That '[:10]' thing is an example of a "slice": it's a way of taking a
chunk out of a sequence. The following examples should help clarify the
idea:
###
>>> numbers = range(42, 47)
>>> numbers
[42, 43, 44, 45, 46]
>>> numbers[2:]
[44, 45, 46]
>>> numbers[:2]
[42, 43]
>>> numbers[2:4]
[44, 45]
>>> numbers[:-1]
[42, 43, 44, 45]
>>> numbers[-1:]
[46]
###
So think of a hot butter knife going through the sequence: that's a slice.
Slices not only work on lists: they also work on strings, as your example
above shows.
For more information on slices, we can look at:
http://www.python.org/doc/tut/node5.html#SECTION005140000000000000000
and for the nitty-gritty, the Library Reference on the topic of
"Sequences":
http://www.python.org/doc/lib/typesseq.html
(Minor note: in Python 2.3, slices will become more versatile. In the
near future, we should be able to reverse a string by doing something like
'mystring[::-1]')
By the way, the code above can can be more idiomatically written as:
if contenttype.startswith("multipart/"):
This has the same effect as the slice-and-compare approach, but using
'startswith()' more clearly describes the intent of the programmer ---
checking that contenttype starts with the prefix "multipart/".
Hope this helps!