The Python 'in' Operator
The operators in
and not in
test for collection membership (a 'collection' refers to a string, list, tuple or dictionary - don't worry, we will cover lists, tuples and dictionaries soon!). The expression
element in coll
evaluates to True
if element
is a member of the collection coll
, and False
otherwise.
The expression
element not in coll
evaluates to True
if element
is not a member of the collection coll
, and False
otherwise.
Note this returns the negation of element in coll
- that is, the expression element not in coll
is equivalent to the expression not (element in coll)
.
Advanced String Slicing
You've seen in lecture that you can slice a string with a call such as s[i:j]
, which gives you a portion of string s
from index i
to index j-1
. However this is not the only way to slice a string! If you omit the starting index, Python will assume that you wish to start your slice at index 0. If you omit the ending index, Python will assume you wish to end your slice at the end of the string. Check out this session with the Python shell:
>>> s = 'Python is Fun!'
>>> s[1:5]
'ytho'
>>> s[:5]
'Pytho'
>>> s[1:]
'ython is Fun!'
>>> s[:]
'Python is Fun!'
That last example is interesting! If you omit both the start and ending index, you get your original string!
There's one other cool thing you can do with string slicing. You can add a third parameter, k
, like this:s[i:j:k]
. This gives a slice of the string s
from index i
to index j-1
, with step size k
. Check out the following examples:
>>> s = 'Python is Fun!'
>>> s[1:12:2]
'yhni u'
>>> s[1:12:3]
'yoiF'
>>> s[::2]
'Pto sFn'
The last example is similar to the example s[:]
. With s[::2]
, we're asking for the full string s
(from index 0 through 13), with a step size of 2 - so we end up with every other character in s
. Pretty cool!
출처
https://courses.edx.org