Boston Python Workshop 4/Twitter handout: Difference between revisions

Content added Content deleted
imported>Jesstess
(Created page with '===Twitter goals=== * practice for loops * practice using functions * practice implementing functions * see what it's like to use an API * have fun collecting data from Twitter …')
 
imported>Jesstess
No edit summary
Line 122: Line 122:
the first argument and an upper bound as the second argument and
the first argument and an upper bound as the second argument and
returns a random integer between those bounds.
returns a random integer between those bounds.

===New Wordplay material summary===

====<code>in</code> keyword====

<code>in is a keyword checking for containment. You can use it in a couple
of ways:

<pre>
>>> "a" in "apple"
True
>>> "z" in "apple"
False</pre>

<pre>
>>> dogs = ["pug", "boxer", "dalmation"]
>>> "tiger" in dogs
False
>>> "pug" in dogs
True</pre>

====Reversing lists====

Here's a quick way to reverse a list.

<pre>
>>> fruits = ["apples", "bananas", "cherries"]
>>> fruits[::-1]
['cherries', 'bananas', 'apples']</pre>

Let's break down why this works:

First, remember that we can get individual elements from lists:

<pre>
>>> fruits[0]
'apples'</pre>

We can also slice lists:

<pre>
>>> fruits[0:2]
['apples', 'bananas']
>>> fruits[:2]
['apples', 'bananas']
>>> fruits[1:]
['bananas', 'cherries']</pre>

We can also make a copy of the list by taking a slice from the
beginning to the end of the list:

<pre>
>>> my_fruits = fruits[:]
['apples', 'bananas', 'cherries']</pre>

There's an extended slicing syntax that let's you say what direction
you want to slice in. By default it is forward, but you can supply a
<code>-1</code> to say backwards:

<pre>
>>> fruits[::-1]
['cherries', 'bananas', 'apples']</pre>

====Regular expressions====

* ^ is an anchor that means "beginning"
* $ is an anchor that means "end"
* . means a single wildcard character
* .* means any number (including zero) of wildcard characters

Examples:

* <code>stuv</code> will match anything that contains "rstu", for example "understudy".
* <code>^aa</code> will match anything that starts with "aa", for example "aardvark".
* <code>a.b.c</code> will match anything containing "a", then any single character, then "b", then any single character, then "c", for example "iambic".
* <code>ss.*ss</code> will match anything containing "ss", then anything, then "ss", for example "messiness".
* <code>^c.d.e$</code> will match anything that starts with "c", then any single character, then d, then any single character, then ends with an "e", for example "cadre".