<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Python Central - Python Programming Examples, Tutorials</title>
	
	<link>http://pythoncentral.org</link>
	<description>Python Programming Examples, Tutorials</description>
	<lastBuildDate>Tue, 15 May 2012 04:23:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/PythonCentral" /><feedburner:info uri="pythoncentral" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>PythonCentral</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Encoding and Decoding Strings (in Python 2.x)</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/T1uScB-xS3Q/</link>
		<comments>http://pythoncentral.org/encoding-and-decoding-strings-in-python-2-x/#comments</comments>
		<pubDate>Wed, 09 May 2012 06:17:56 +0000</pubDate>
		<dc:creator>Joanna Alonzo</dc:creator>
				<category><![CDATA[Learn Python Guide]]></category>
		<category><![CDATA[Python Tips and Tricks]]></category>
		<category><![CDATA[decoding in python]]></category>
		<category><![CDATA[encoding in python]]></category>
		<category><![CDATA[non-ASCII characters in Python]]></category>
		<category><![CDATA[python string decoding]]></category>
		<category><![CDATA[python string encoding]]></category>
		<category><![CDATA[python strings]]></category>
		<category><![CDATA[unicode strings in python]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=419</guid>
		<description><![CDATA[Strings are among the most commonly used data types in Python, and there might be times when you want to (or have to) work with strings containing or entirely made up of characters outside of the standard ASCII set (e.g. characters with accents or other markings). Python 2.x provides a data type called a Unicode<a class="moretag" href="http://pythoncentral.org/encoding-and-decoding-strings-in-python-2-x/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>Strings are among the most commonly used data types in Python, and there might be times when you want to (or have to) work with strings containing or entirely made up of characters outside of the standard ASCII set (e.g. characters with accents or other markings).</p>
<p>Python 2.x provides a data type called a <em>Unicode string</em> for working with Unicode data using string encoding and decoding methods.</p>
<p>In order to figure out what “encoding” and “decoding” is all about, let’s look at an example string:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;s = &quot;Flügel&quot;
</pre>
<p>We can see our string <em>s</em> has a non-ASCII character in it, namely “ü” or “umlaut-u.” Assuming we’re in the standard Python 2.x IDLE GUI, let’s see what happens when we reference the string, and when it’s printed:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;s
'Fl\xfcgel'
&gt;&gt;&gt;print s
Flügel
</pre>
<p>Printing gave us the value that we assigned to the variable, but something obviously happened along the way that turned it from what we typed into the interpreter to something seemingly incomprehensible. The non-ASCII character “ü” was translated into a code phrase, i.e. “\xfc,“ by a set of rules behind-the-scenes. In other words, it was <em>encoded</em>.</p>
<p>At this point, <em>s</em> is an 8-bit string, which to us basically means it isn’t a Unicode string. Let’s examine how to make a Unicode string with the same data. The simplest way is with a “u” prefix in front of the literal string marking it as a Unicode string:</p>
<pre class="brush: python; title: ; notranslate">
u = u&quot;Flügel&quot;
</pre>
<p>If we reference and print <em>u</em> like we did with <em>s</em>, we’ll find something similar:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;u
u'Fl\xfcgel'
&gt;&gt;&gt;print u
Flügel
</pre>
<p>We can see that the code phrase for our “umlaut-u” is still “\xfc“ and it prints the same—so does that mean our Unicode string is encoded the same way as our 8-bit string <em>s</em>? To figure that out let’s look at what the encode() method does when we try it on <em>u</em> and <em>s</em>:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;u.encode('latin_1')
'Fl\xfcgel'
&gt;&gt;&gt;s.encode('latin_1')
Traceback (most recent call last):
   File &quot;&lt;pyshell#35&gt;&quot;, line 1, in &lt;module&gt;
   s.encode('latin_1')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 2: ordinal not in range(128)
</pre>
<p>Now it seems encoding the Unicode string (with the ‘latin-1’ encoding) retuned the same value as string <em>s</em>, but the encode() method didn’t work on string <em>s</em>. Since we couldn’t encode <em>s</em>, what about decoding it? Will it give us the same value as <em>u</em>? Let’s find out:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;s.decode('latin-1')
u'Fl\xfcgel'
</pre>
<p>That’s exactly what it does after all. So then, what difference does it make that <em>s</em> is an 8-bit string and <em>u</em> is a Unicode string? They behave the same way, don’t they?  In our “umlaut-u” example, there seemed to be little difference, aside from the “u” hanging out in front of the Unicode string.</p>
<p>Well, the difference is that the Unicode string <em>u</em> was using a code phrase that the Unicode standard defines for the character “umlaut-u,” and the 8-bit string <em>s</em> was using a code phrase that the ‘latin-1’ codec (rule-set) defines for “umlaut-u.”</p>
<p>OK, well…that’s great, but…they were still the same, right? So why does that matter?</p>
<p>To illustrate the difference and why it matters, let’s consider a new 8-bit string:</p>
<pre class="brush: python; title: ; notranslate">
new_s = '\xe5\xad\x97'
</pre>
<p>Unlike the first one, our new 8-bit string is <em>only</em> code phrases—completely incomprehensible.</p>
<p>Why didn’t we just type in (or copy-and-paste) the characters like the last 8-bit string? Well, assuming we’re still using the standard Python 2x IDLE, we <em>couldn’t</em> type or paste this value into the interpreter—it would not accept the value if we did. Why? Because our <em>new_s</em> is an encoded string for an Asian script character (yes, only one character), and IDLE is averse to such input (if you have the appropriate input keyboard installed for your system you can try this and find out).</p>
<p>The question now is how can we turn these code phrases into the character they’re supposed to display? In the first example using a print statement on <em>s</em> worked fine, so it should be the same with <em>new_s</em>, right? Let’s see what our unknown Asian script character is:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;print new_s
å­—
</pre>
<p>Uh-oh…that isn’t right. First of all, that is not an Asian script character. Secondly, it’s more than one character.  Simply referencing <em>new_s</em> would give us the string we assigned to it, and <em>print</em> didn’t seem to work. Let’s see if a Unicode string will help us out.</p>
<p>To create our new Unicode string <em>new_u</em>, we can’t follow the method in our first example—to do that we’d have to input the literal character of our string with a “u” prefix (we haven’t seen our character yet, and anyway IDLE wouldn’t accept it as input).</p>
<p>However, we did get the value of <em>u</em> by <span style="text-decoration: underline;">decoding</span> <em>s</em>, so in the same way we should be able to get the value for our <em>new_u</em> by decoding <em>new_s</em>. Let’s try decoding as we did in the first example:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;new_u = new_s.decode('latin_1')
&gt;&gt;&gt;new_u
u'\xe5\xad\x97'
</pre>
<p>Great, now that we’ve stored the decoded <em>new_s</em> string value using the same method as in our first example, let’s print our Unicode string and see what our script character is:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;print new_u
å
</pre>
<p>­Uh…Isn’t that the same thing we got when we tried to print the ­­<em>new_s</em> string?? So then using the Unicode string really isn’t any different?</p>
<p>Not so fast—there’s one detail that was purposefully glossed-over to prove a point: the encoding we used to decode the string is the same as the first example, the ‘latin-1’ codec. However, the 8-bit string <em>new_s</em> was <strong>not</strong> encoded in ‘latin-1,’ it was encoded in ‘utf-8.’</p>
<p>OK, so there was no way for you really to know that unless explicitly told, but this still illustrates the point: <strong>the encoding/codec/rule-set makes all the difference when encoding/decoding strings.</strong></p>
<p>With the right encoding, let’s see what happens:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;new_u = new_s.decode('utf_8')
&gt;&gt;&gt;new_u
u'\u5b57'
&gt;&gt;&gt;print new_u
字
</pre>
<p>FINALLY! Our long-lost script character has been found, and it looks pretty good. Now, try copying-and-pasting the character as input—you’ll find it doesn&#8217;t work (we’re still talking about Python 2x IDLE).</p>
<p>You might also notice something different about the value of <em>new_u</em>, i.e. it appears to consist of only one code phrase (this time in the form ‘\uXXXX’). This Unicode standard has a unique code phrase for <span style="text-decoration: underline;">every</span> character or script character that can possibly be displayed on your screen. With that in mind you can also tell that the first time we tried to decode <em>new_s,</em> the value was wrong (“u’\xe5\xad\x97’” has 3 code phrases, and for the Unicode standard, that means 3 unique characters).</p>
<p>Well, now that those annoying examples are finished, let’s recap the main points of all this hoopla:</p>
<ol>
<li>Strings are one of the most common data types in Python, and sometimes they’ll include non-ASCII characters.</li>
<li>When strings contain non-ASCII characters, they can either be 8-bit strings (<strong>encoded strings</strong>), or they can be Unicode strings (<strong>decoded strings</strong>).</li>
<li>To print or display some strings properly, they need to be <strong>decoded</strong> (Unicode strings).</li>
<li><strong>THE ENCODING/CODEC MAKES ALL THE DIFFERENCE WHEN ENCODING/DECODING STRINGS.</strong></li>
</ol>
<p>The encoding/codec is like the DNA of your string—even with the same nutrients (input), using the wrong DNA (codec) will give you an orange when you should have had an apple.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/G3nhTpAelYmhs6HRtcrN6CA5Z3Q/0/da"><img src="http://feedads.g.doubleclick.net/~a/G3nhTpAelYmhs6HRtcrN6CA5Z3Q/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/G3nhTpAelYmhs6HRtcrN6CA5Z3Q/1/da"><img src="http://feedads.g.doubleclick.net/~a/G3nhTpAelYmhs6HRtcrN6CA5Z3Q/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/T1uScB-xS3Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/encoding-and-decoding-strings-in-python-2-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/encoding-and-decoding-strings-in-python-2-x/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=encoding-and-decoding-strings-in-python-2-x</feedburner:origLink></item>
		<item>
		<title>Lists and Tuples</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/fCNDLN5qT7I/</link>
		<comments>http://pythoncentral.org/lists-and-tuples/#comments</comments>
		<pubDate>Wed, 09 May 2012 06:10:30 +0000</pubDate>
		<dc:creator>Joanna Alonzo</dc:creator>
				<category><![CDATA[Learn Python Guide]]></category>
		<category><![CDATA[Python data types]]></category>
		<category><![CDATA[Python lists]]></category>
		<category><![CDATA[Python lists and tuples]]></category>
		<category><![CDATA[Python sequences]]></category>
		<category><![CDATA[Python tuples]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=436</guid>
		<description><![CDATA[Two of the most commonly used built-in data types in Python are the list and the tuple. Lists and tuples are part of the group of sequence data types—in other words, lists and tuples store one or more objects or values in a specific order. The objects stored in a list or tuple can be<a class="moretag" href="http://pythoncentral.org/lists-and-tuples/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>Two of the most commonly used built-in data types in Python are the <em>list</em> and the <em>tuple</em>.</p>
<p>Lists and tuples are part of the group of <em>sequence</em> data types—in other words, lists and tuples store one or more objects or <em>values</em> in a specific order. The objects stored in a list or tuple can be of any type, including the “nothing” type defined by the <em>None</em> keyword.</p>
<p>The big difference between lists and tuples is that lists are mutable, but tuples are immutable, meaning once tuples are created, objects can’t be added or removed, and the order cannot be changed. However, certain objects in tuples can be changed, as we’ll see later.</p>
<p>Creating a list or tuple is easy, here are some empty ones:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;emptylst = [] # lists must be surrounded by brackets
&gt;&gt;&gt;emptytup = () # tuples may or may not be surrounded by parenthesis
</pre>
<p>To create non-empty lists or tuples,<em> values </em>are separated by commas:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;lst = [1, 2, 3] # lists must be surrounded by brackets
&gt;&gt;&gt;lst
[1, 2, 3]
</pre>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;tup = 1, 2, 3 # tuples may or may not be surrounded by parenthesis
&gt;&gt;&gt;tup
(1, 2, 3)
</pre>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;tup = ('one', 'two', 'three')
&gt;&gt;&gt;tup
('one', 'two', 'three')
</pre>
<p><strong>Note:</strong> To create a tuple with only one <em>value</em>, add a trailing comma to the value.</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;tup2 = 0, # the length of this tuple is 1
&gt;&gt;&gt;tup2
(0,)
</pre>
<p>The values in lists and tuples, as with other sequence types, are referenced by <em>index </em>(beginning with 0 for  the first value):</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;lst[0]
1
&gt;&gt;&gt;tup[1]
'two'
</pre>
<p>Using an index below zero gets the values starting from the <span style="text-decoration: underline;">end</span> of the list or tuple:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;lst[-1]
3
&gt;&gt;&gt;tup[-2]
'two'
</pre>
<p>Multiple values can be referenced by “slicing” the list or tuple (referencing a range [start : stop] ):</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;lst[0:2]
[1, 2]
&gt;&gt;&gt;tup[1:5] # note an out-of-range stopindex translates to the end
('two', 'three')
</pre>
<p><em>Values</em> for lists can be assigned with indexes (as long as the index already exists), but <span style="text-decoration: underline;">not</span> for tuples:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;lst[2] = 'three'
&gt;&gt;&gt;lst
[1, 2, 'three']
&gt;&gt;&gt;tup[2] = 3
Traceback (most recent call last):
   File &quot;&lt;pyshell#68&gt;&quot;, line 1, in &lt;module&gt;
   tup[2] = 3
TypeError: 'tuple' object does not support item assignment
</pre>
<p>Values can also be added to lists (and lists can be combined) with the ‘+’ operator, or with the standard append() method:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;lst += [None] # concatenation, the same as lst = lst + [None]
&gt;&gt;&gt;lst
[1, 2, 'three', None]
&gt;&gt;&gt;lst.append(5)
&gt;&gt;&gt;lst
[1, 2, 'three', None, 5]
</pre>
<p>Values can be removed from lists with the del keyword:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;del lst[3]
&gt;&gt;&gt;lst
[1, 2, 'three', 5]
&gt;&gt;&gt;del lst[2:] # slicing deletion; no stopindex means through the end
&gt;&gt;&gt;lst
[1, 2]
</pre>
<p>Assignment and deletion methods for lists don’t work for tuples, but concatenation works:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;tup += (4,) # note only tuples can be added to tuples
&gt;&gt;&gt;tup
('one', 'two', 'three', 4)
</pre>
<p>Even though tuples are not mutable like lists, with the slicing technique and a little creativity tuples can be manipulated like lists:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;tup = tup[0:2] # almost like slice deletion
&gt;&gt;&gt;tup
('one', 'two')
&gt;&gt;&gt;tup2 += tup
&gt;&gt;&gt;tup2
&gt;&gt;&gt;tup2 = tup2[0:1] + (1,) + tup2[2:] # almost like index assignment
&gt;&gt;&gt;tup2
(0, 1, 'two')
</pre>
<p>In addition, if a tuple contains a list, the mutability of the list in that tuple is preserved:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;tup3 = 0, 'one', None, []
&gt;&gt;&gt;tup3[3].append('three')
&gt;&gt;&gt;tup3
(0, 'one', None, ['three'])
</pre>
<p>Aside from the methods described here more exist for lists and tuples, but these cover  the most common operations. And remember, lists and tuples can be <strong>nested</strong> (can contain lists and tuples, and other data types that store sets of <em>values</em>, such as dictionaries), and can store different types simultaneously, making them very useful.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/-ajrKTbNlBOE_5nPrmCg-Bj7dZo/0/da"><img src="http://feedads.g.doubleclick.net/~a/-ajrKTbNlBOE_5nPrmCg-Bj7dZo/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/-ajrKTbNlBOE_5nPrmCg-Bj7dZo/1/da"><img src="http://feedads.g.doubleclick.net/~a/-ajrKTbNlBOE_5nPrmCg-Bj7dZo/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/fCNDLN5qT7I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/lists-and-tuples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/lists-and-tuples/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=lists-and-tuples</feedburner:origLink></item>
		<item>
		<title>Dictionaries</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/6LFulT-zt90/</link>
		<comments>http://pythoncentral.org/dictionaries/#comments</comments>
		<pubDate>Wed, 09 May 2012 06:01:42 +0000</pubDate>
		<dc:creator>Joanna Alonzo</dc:creator>
				<category><![CDATA[Learn Python Guide]]></category>
		<category><![CDATA[dictionaries in Python]]></category>
		<category><![CDATA[Python data types]]></category>
		<category><![CDATA[Python dictionaries]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=443</guid>
		<description><![CDATA[Among the built-in Python data types is a very versatile type called a dictionary. Dictionaries are similar to lists and tuples because they act as storage units for other objects or variables you’ve created. Dictionaries are different from lists and tuples because the group of objects they hold aren’t in any particular order, but rather<a class="moretag" href="http://pythoncentral.org/dictionaries/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>Among the built-in Python data types is a very versatile type called a <em>dictionary</em>. Dictionaries are similar to lists and tuples because they act as storage units for other objects or variables you’ve created. Dictionaries are different from lists and tuples because the group of objects they hold aren’t in any particular order, but rather each object has its own unique “name,” commonly known as a <em>key</em>.</p>
<p>The objects or <em>values</em> stored in a dictionary can basically be anything (even the “nothing” type defined as None), but <em>keys</em> can only be immutable type-objects&#8211;e.g., <em>strings</em>, <em>tuples</em>, <em>integers</em>, etc.</p>
<p><strong>Note</strong>: Immutable types that store objects like <em>tuples</em> can <span style="text-decoration: underline;">only</span> contain other immutable types to be dictionary <em>keys</em>.</p>
<p>Creating a dictionary is easy, here is an empty one:</p>
<pre class="brush: python; title: ; notranslate">emptydict = {}</pre>
<p>Here is one with a few values (note the { <em>key1</em>: <em>value1, key2: value2, …</em>} structure) :</p>
<pre class="brush: python; title: ; notranslate">smalldict = { 'dlist': [], 'dstring': 'pystring', 'dtuple': (1, 2, 3) }</pre>
<p>You can also use the dictionary constructor (note with this method <em>keys</em> can only be keyword strings):</p>
<pre class="brush: python; title: ; notranslate">smalldict = dict(dlist=[], dstring='pystring', dtuple=(1, 2, 3))</pre>
<p>To get one of the values, just use its key:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;smalldict = {'dlist': [], 'dstring': 'pystring', 'dtuple': (1, 2, 3)}
&gt;&gt;&gt;smalldict['dstring']
'pystring'
</pre>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;smalldict['dtuple']
(1, 2, 3)
</pre>
<p>To remove a <em>key: value</em>pair, simply delete it with del</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;del smalldict['dlist']
&gt;&gt;&gt;smalldict
{'dstring': 'pystring', 'dtuple': (1, 2, 3)}
</pre>
<p>Or to assign a new <em>key</em>, just use the new <em>key</em>:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;smalldict['newkey'] = None
&gt;&gt;&gt;smalldict
{'dstring': 'pystring', 'newkey': None, 'dtuple': (1, 2, 3)}
</pre>
<p><strong>Note: </strong>All the keys in a dictionary are unique, so if you assign a value to an existing key, it will be overwritten! For example:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;smalldict['dstring'] = 'new pystring'
&gt;&gt;&gt;smalldict
{'dstring': 'new pystring', 'newkey': None, 'dtuple': (1, 2, 3)}
</pre>
<p>If you want to change the <em>key</em> for a <em>value</em>, you can create the new <em>key</em> with the <em>value</em>, then simply delete the old <em>key</em>:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;smalldict['changedkey'] = smalldict['newkey']
&gt;&gt;&gt;del smalldict['newkey']
&gt;&gt;&gt;smalldict
{'dstring': 'new pystring', 'changedkey': None, 'dtuple': (1, 2, 3)}
</pre>
<p>To check if a <em>key</em> exists in the dictionary, just use <em>key</em> in smalldict:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;'dstring' in smalldict
True
</pre>
<p><strong>Note:</strong> This does <span style="text-decoration: underline;">not</span> check whether a <em>value</em> exists in the dictionary, only a <em>key</em>:</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;'new pystring' in smalldict
False
</pre>
<p>To check for a <em>value</em>, you can use one of the dictionary’s standard methods, viewvalues():</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt;'new pystring' in smalldict.viewvalues()
True
</pre>
<p>There are many more useful methods and recipes for dictionary objects, but those are the basics.</p>
<p>Remember, <em>keys</em> don’t have to be strings, but can be any immutable object you can create—and values can be just about anything, including other dictionaries. Don’t be afraid to be creative and discover what you can do with them!</p>

<p><a href="http://feedads.g.doubleclick.net/~a/0LjgnyJiZsYy6GQxsTnPs04XXas/0/da"><img src="http://feedads.g.doubleclick.net/~a/0LjgnyJiZsYy6GQxsTnPs04XXas/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/0LjgnyJiZsYy6GQxsTnPs04XXas/1/da"><img src="http://feedads.g.doubleclick.net/~a/0LjgnyJiZsYy6GQxsTnPs04XXas/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/6LFulT-zt90" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/dictionaries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/dictionaries/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=dictionaries</feedburner:origLink></item>
		<item>
		<title>Introduction to IPython: An Enhanced Python Interpreter</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/H4vSPjjXz28/</link>
		<comments>http://pythoncentral.org/introduction-to-ipython-an-enhanced-python-interpreter/#comments</comments>
		<pubDate>Wed, 25 Apr 2012 22:06:20 +0000</pubDate>
		<dc:creator>Joanna Alonzo</dc:creator>
				<category><![CDATA[Python Distributions]]></category>
		<category><![CDATA[IPython]]></category>
		<category><![CDATA[IPython benefits]]></category>
		<category><![CDATA[IPython configuration]]></category>
		<category><![CDATA[IPython introduction]]></category>
		<category><![CDATA[IPython setup]]></category>
		<category><![CDATA[IPython toolkit]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=400</guid>
		<description><![CDATA[Simply put, IPython lets you do all sorts of really powerful stuff. It&#8217;s very popular amongst scientists and mathematicians, and has a lot of features that they seem to really appreciate. It also has a lot of features that are really useful to everyone else who uses Python. IPython offers lots of simple hooks for<a class="moretag" href="http://pythoncentral.org/introduction-to-ipython-an-enhanced-python-interpreter/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>Simply put, IPython lets you do all sorts of really powerful stuff. It&#8217;s very popular amongst scientists and mathematicians, and has a lot of features that they seem to really appreciate. It also has a lot of features that are really useful to everyone else who uses Python.</p>
<p>IPython offers lots of simple hooks for you to customise and extend the way it works. Because it&#8217;s so easy to modify what IPython does, it can be quite difficult to define exactly what it is. When you first install it, you get an app that essentially boils down to an enhanced, Python, interactive interpreter. You can do all the stuff you can do in a regular, interactive session, and you can do quite a bit more.</p>
<p dir="ltr"><strong>Magic Commands</strong></p>
<p>The very first feature you&#8217;ll notice is the coloured prompt, a green In [1]: . Colour&#8217;s always cool, and it&#8217;s put to good use, but IPython&#8217;s not just a pretty stack trace. A more powerful enhancement to the standard Python session is the use of Magic Commands &#8211; Python functions that you can call using a shell-like syntax. You get a bunch built in, some really clever ones, and you can easily define your own. To use a magic, you just type its name, then any arguments, separated by a space:</p>
<pre class="brush: bash; title: ; notranslate">magicname arg0 arg1</pre>
<p>Some of the built-in magics are there to make the Python session operate more like a conventional shell. You have cd, ls, cp and so on. If you like to use these commands, you can just type them in as you normally would:</p>
<pre class="brush: bash; title: ; notranslate">cd ~/scripts</pre>
<p>If you want to use shell commands that you don&#8217;t have a magic set up for, you can just start the line with a bang and write any command that would normally work:</p>
<pre class="brush: bash; title: ; notranslate">!echo IPython</pre>
<p><strong>Editing the Namespace</strong></p>
<p>One of the most useful magics, I think, is edit. If you want to write any moderately complex Python, you don&#8217;t want to do it at the command line. In IPython, rather than starting with a text editor, then running the file, as you normally would, the process is reversed: We start at the prompt and simply invoke an editor from within the session. You can use any editor you like for this, but Vim rules.</p>
<p>You can use edit by just entering &#8216;edit&#8217; at the prompt. IPython will open your editor with an empty tempfile. When you save and exit the editor, any code you wrote is injected into the namespace.</p>
<p>For example, you could enter &#8216;edit&#8217; at the prompt, then define a function named spam in your editor, then save the file and exit the editor, then call spam at the prompt, passing whatever arguments you like. What&#8217;s especially cool, if you later enter &#8216;edit spam&#8217; at the prompt, IPython reopens whichever tempfile contains spam, so you can edit it some more.</p>
<p>There&#8217;s also ways to inject the contents of regular files into the same namespace. And, of course, you can save what you&#8217;ve built, using your editor&#8217;s save feature, or just writing stuff to files from the command line. There&#8217;s also a magic named <em>store</em> that you can use to make objects persist across sessions.</p>
<p>The ability to easily build a namespace interactively, developing it as you go, gives you much more freedom to explore and interact with the objects you&#8217;re creating. This approach is a natural fit for writing Python, which you&#8217;d normally develop rapidly and in very small increments.</p>
<p><strong>Configuring the Interpreter</strong></p>
<p>IPython has a powerful configuration system, which is pure Python itself. You can use it to create and manage any number of configurations, customising each of IPython&#8217;s features, as well as specifying code to be automatically injected into new sessions, further enhancing your ability to fully customise the way your interpreter works.</p>
<p>Pretty much everything is configurable, and, if you know a little Python, it&#8217;s easy to do.</p>
<p><strong>Developing your Environment</strong></p>
<p>Once you&#8217;re comfortable using IPython, you should check out other articles on Python Central that cover the main features in more detail, including defining your own magic commands and configuring sessions.</p>
<p>Over time, as you use IPython more, and add more to it, you develop a heavily customised, console IDE, conveniently wrapping everything else you&#8217;re doing in Python.</p>
<p>Grab a copy from <a href="http://ipython.org" target="_blank">ipython.org</a>, and let us know where you end up going with it.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/MHEXllyVvn1AjPbpbTezb_FXP7I/0/da"><img src="http://feedads.g.doubleclick.net/~a/MHEXllyVvn1AjPbpbTezb_FXP7I/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/MHEXllyVvn1AjPbpbTezb_FXP7I/1/da"><img src="http://feedads.g.doubleclick.net/~a/MHEXllyVvn1AjPbpbTezb_FXP7I/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/H4vSPjjXz28" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/introduction-to-ipython-an-enhanced-python-interpreter/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/introduction-to-ipython-an-enhanced-python-interpreter/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=introduction-to-ipython-an-enhanced-python-interpreter</feedburner:origLink></item>
		<item>
		<title>Working with Threads in Python</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/5xgh_nHuSLc/</link>
		<comments>http://pythoncentral.org/working-with-threads-in-python/#comments</comments>
		<pubDate>Tue, 24 Apr 2012 22:31:01 +0000</pubDate>
		<dc:creator>Joanna Alonzo</dc:creator>
				<category><![CDATA[General Programming Tips]]></category>
		<category><![CDATA[Learn Python Guide]]></category>
		<category><![CDATA[python multi threading]]></category>
		<category><![CDATA[python threading]]></category>
		<category><![CDATA[Python threads]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=374</guid>
		<description><![CDATA[What are threads? Simply put, try to imagine them as running several programs concurrently, in a single process. When you create one or more threads in your program, they get executed simultaneously, independent of each other, and most importantly, they can share information among them without any extra difficulty. These features make threads lightweight and<a class="moretag" href="http://pythoncentral.org/working-with-threads-in-python/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>What are threads? Simply put, try to imagine them as running several programs concurrently, in a single process. When you create one or more threads in your program, they get executed simultaneously, independent of each other, and most importantly, they can share information among them without any extra difficulty.</p>
<p>These features make threads lightweight and handy in situations like network programming, when you try to ping (send network packets or requests) hundreds of workstations and you don&#8217;t want to ping them one after another! Since network replies may come after a significant amount of delay, the program will be extremely slow if you don&#8217;t ping many workstations concurrently.</p>
<p>Threading in Python is easy. First thing you need to do is to import Thread using the following code:</p>
<pre class="brush: python; title: ; notranslate">from threading import Thread</pre>
<p>Next, you will want to make your class work as a thread. For this, you should subclass your class from the Thread class:</p>
<pre class="brush: python; title: ; notranslate">class MyThread(Thread):</pre>
<p>Now, our <em>MyThread</em> class is a child class of Thread class. We then define a <em>run()</em> method in our class. This function will be executed when we call the <em>start()</em> method of any object of our <em>MyThread</em> class.</p>
<p>The code of the complete class is shown below. We use the sleep() function to make the thread “sleep” i.e. prevent it from executing for a random amount of time. If we don’t do this, the code will be executed so quickly that we will not be able to notice any worthwhile changes.</p>
<pre class="brush: python; title: ; notranslate">class MyThread(Thread):
   def __init__(self, val):
      &quot;&quot;&quot;
         Constructor
      &quot;&quot;&quot;
      Thread.__init__(self)
      self.val = val

   def run(self):
      for i in range(1, self.val):
         print &quot;Value %d in thread %s&quot; % (i, self.getName())
         # Sleep for random time between 1 ~ 3 second
         secondsToSleep = randint(1, 5)
         print &quot;%s sleeping fo %d seconds...&quot; % (self.getName(), secondsToSleep)
         time.sleep(secondsToSleep)</pre>
<p>The next step is to create some objects (two in this example) of our thread-supported class. We call the <em>start()</em> method of each object – this in turn executes the <em>run()</em> method of each object.</p>
<pre class="brush: python; title: ; notranslate"># Run following code when the program starts
if __name__ == &quot;__main__&quot;:
   # Declare objects of MyThread class
   myThreadOb1 = MyThread(4)
   myThreadOb1.setName(&quot;Thread 1&quot;)

   myThreadOb2 = MyThread(4)
   myThreadOb2.setName(&quot;Thread 2&quot;)

   # Start running the threads!
   myThreadOb1.start()
   myThreadOb2.start()
   # Wait for the threads to finish...
   myThreadOb1.join()
   myThreadOb2.join()

   print &quot;Main Terminating...&quot;</pre>
<p>That&#8217;s it! Note that we need to call the<em> join()</em> method of each object – otherwise, the program will terminate before the threads complete their execution.</p>
<p>The complete version of the program looks like this:</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python
from threading import Thread
from random import Random
import time
from Crypto.Random.random import randint

class MyThread(Thread):

   def __init__(self, val):
      &quot;&quot;&quot;
         Constructor
      &quot;&quot;&quot;
      Thread.__init__(self)
      self.val = val

   def run(self):
      for i in range(1, self.val):
         print &quot;Value %d in thread %s&quot; % (i, self.getName())
         # Sleep for random time between 1 ~ 3 second
         secondsToSleep = randint(1, 5)
         print &quot;%s sleeping fo %d seconds...&quot; % (self.getName(), secondsToSleep)
         time.sleep(secondsToSleep)

# Run following code when the program starts
if __name__ == &quot;__main__&quot;:
   # Declare objects of MyThread class
   myThreadOb1 = MyThread(4)
   myThreadOb1.setName(&quot;Thread 1&quot;)

   myThreadOb2 = MyThread(4)
   myThreadOb2.setName(&quot;Thread 2&quot;)

   # Start running the threads!
   myThreadOb1.start()
   myThreadOb2.start()
   # Wait for the threads to finish...
   myThreadOb1.join()
   myThreadOb2.join()

   print &quot;Main Terminating...&quot;</pre>

<p><a href="http://feedads.g.doubleclick.net/~a/aTVLBgekt3gkCL7ZCkMaE3cM00I/0/da"><img src="http://feedads.g.doubleclick.net/~a/aTVLBgekt3gkCL7ZCkMaE3cM00I/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/aTVLBgekt3gkCL7ZCkMaE3cM00I/1/da"><img src="http://feedads.g.doubleclick.net/~a/aTVLBgekt3gkCL7ZCkMaE3cM00I/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/5xgh_nHuSLc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/working-with-threads-in-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/working-with-threads-in-python/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=working-with-threads-in-python</feedburner:origLink></item>
		<item>
		<title>Working With Packages in Python</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/-iQlzphC5fE/</link>
		<comments>http://pythoncentral.org/working-with-packages-in-python/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 21:42:39 +0000</pubDate>
		<dc:creator>Joanna Alonzo</dc:creator>
				<category><![CDATA[Learn Python Guide]]></category>
		<category><![CDATA[import]]></category>
		<category><![CDATA[Python class organization]]></category>
		<category><![CDATA[Python directories]]></category>
		<category><![CDATA[Python file organization]]></category>
		<category><![CDATA[Python packages]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=302</guid>
		<description><![CDATA[When you&#8217;ve got a large number of classes, you&#8217;ll want to organize them in packages. When the number of modules (simply stated, a module might be just a file containing some classes) in any project grows significantly, it is wiser to organize them in Packages – that is, placing functionally similar modules/classes in the same directory. Working with packages<a class="moretag" href="http://pythoncentral.org/working-with-packages-in-python/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;ve got a large number of classes, you&#8217;ll want to organize them in packages. When the number of modules (simply stated, a module might be just a file containing some classes) in any project grows significantly, it is wiser to organize them in Packages – that is, placing functionally similar modules/classes in the same directory.</p>
<p>Working with packages is really simple. All you need to do is:</p>
<ul>
<li>Create a directory &amp; give it your package&#8217;s name</li>
<li>Put your classes in it</li>
<li>Create an <strong>__init__.py</strong> file in the directory</li>
</ul>
<p>That&#8217;s all! The <strong>__init__.py</strong> file is necessary because with this file, python will know that this directory is a python package directory other than ordinary directories (or folders – whatever you call it). Anyway, it is in this file where we&#8217;ll write some import statements to import classes from our brand new package.</p>
<p><strong>Step 1: Create the package directory</strong><br />
In this tutorial, we will create an <em>“Animals”</em> package – which simply contains two module files named <em>“Mammals”</em> &amp; <em>“Birds”</em> containing <em><strong>Mammals </strong></em>&amp;<strong> </strong><em><strong>Birds</strong></em> classes, respectively.</p>
<p>So, first we create a directory and rename it to <em><strong>“Animals”</strong></em>.</p>
<p><strong>Step 2 – Create some classes for our package</strong><br />
Now, we create the two classes for our package. First, create a file named <em><strong>“Mammals.py”</strong></em> inside the <em>Animals</em> directory and put the following code in it:</p>
<pre class="brush: python; title: ; notranslate">class Mammals:
   def __init__(self):
      &quot;&quot;&quot;
      Constructor for this class
      &quot;&quot;&quot;
      # Create some member animals
      self.members = ['Tiger', 'Elephant', 'Wild Cat']
   def printMembers(self):
      print &quot;Printing members of Mammals Class:&quot;
      for x in self.members:
         print &quot;%s &quot; % x</pre>
<p>The code is pretty much self-explanatory! The class has a property named <em>members</em> – which is a list of some mammals we might be interested in. It also has a method named <em>printMembers</em> which simply prints the list of mammals of this class!</p>
<p>Next we create another class named Birds. Create a file named <em><strong>“Birds.py”</strong></em> inside<br />
the <em>Animals</em> directory and put the following code in it:</p>
<pre class="brush: python; title: ; notranslate">class Birds:
   def __init__(self):
      &quot;&quot;&quot;
      Constructor for this class
      &quot;&quot;&quot;
      # Create some member animals
      self.members = ['Sparrow', 'Robin', 'Duck']
   def printMembers(self):
      print &quot;Printing members of Birds Class:&quot;
      for x in self.members:
         print &quot;%s &quot; % x </pre>
<p>This code is similar to the code we presented for the <em>Mammals</em> class.</p>
<p><strong>Step 3 – Create the “__init__.py” file</strong><br />
Finally, we create a file named <strong>“__init__.py”</strong> inside the <em>Animals</em> directory and put the following code in it:</p>
<pre class="brush: python; title: ; notranslate">from Mammals import Mammals
from Birds import Birds</pre>
<p>That&#8217;s it! We are now ready to test our code! For testing, we create a simple file named “test.py” in the same directory where “Animals” directory is located. We place the following code in the <em>test.py</em> file:</p>
<pre class="brush: python; title: ; notranslate">#!/usr/bin/env python
# Import classes from your brand new package
from Animals import Mammals
from Animals import Birds
# Create an object of Mammals class &amp; call a method of it
myMammal = Mammals()
myMammal.printMembers()
# Create an object of Birds class &amp; call a method of it
myBird = Birds()
myBird.printMembers()</pre>
<p>The code is well-documented, and the complete project is also available for you to download! Check out the source code &amp; directory organization there if anything confuses you.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/-JQHhSv6tyW37rYWnBRPRuqcgMw/0/da"><img src="http://feedads.g.doubleclick.net/~a/-JQHhSv6tyW37rYWnBRPRuqcgMw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/-JQHhSv6tyW37rYWnBRPRuqcgMw/1/da"><img src="http://feedads.g.doubleclick.net/~a/-JQHhSv6tyW37rYWnBRPRuqcgMw/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/-iQlzphC5fE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/working-with-packages-in-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/working-with-packages-in-python/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=working-with-packages-in-python</feedburner:origLink></item>
		<item>
		<title>Adding Watermarks to Images (Watermark Tutorial 1)</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/IU08VuRG4vI/</link>
		<comments>http://pythoncentral.org/adding-watermarks-to-images-watermark-tutorial-1/#comments</comments>
		<pubDate>Sun, 08 Apr 2012 12:46:50 +0000</pubDate>
		<dc:creator>Joanna Alonzo</dc:creator>
				<category><![CDATA[Python Recipes]]></category>
		<category><![CDATA[image watermark]]></category>
		<category><![CDATA[python image watermark]]></category>
		<category><![CDATA[python tutorials]]></category>
		<category><![CDATA[watermark image]]></category>
		<category><![CDATA[watermarks]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=280</guid>
		<description><![CDATA[When you take photographs and post it onto the internet, it is advisable to add a watermark to prevent and discourage unauthorized copies or image theft. Below is a simple python script that uses the PIL image module. It adds a visible text watermark to the image using the system font. We start with importing<a class="moretag" href="http://pythoncentral.org/adding-watermarks-to-images-watermark-tutorial-1/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>When you take photographs and post it onto the internet, it is advisable to add a watermark to prevent and discourage unauthorized copies or image theft.</p>
<p>Below is a simple python script that uses the PIL image module. It adds a visible text watermark to the image using the system font.</p>
<pre class="brush: python; title: ; notranslate">from PIL import Image, ImageDraw, ImageFont, ImageEnhance
import sys

FONT = &quot;Arial.ttf&quot;</pre>
<p>We start with importing the PIL modules and load the Truetype font ‘Arial.ttf’.  By default, it searches for the font in the same folder and then it looks into your font directory (eg: C:/Windows/Fonts)</p>
<pre class="brush: python; title: ; notranslate">def add_watermark(in_file, text, out_file=&quot;watermark.jpg&quot;, angle=23, opacity=0.25): </pre>
<p>We define a function ‘add_watermark’ and declare some default parameters.</p>
<ul>
<li><strong>in_file</strong> – input file</li>
<li><strong>text</strong> – the watermark text</li>
<li><strong>out_file</strong> – output file (default: watermark.jpg)</li>
<li><strong>angle</strong> – angle of the watermark (default: 23 degrees)</li>
<li><strong>opacity</strong> – opaque level for watermark (default: 0.25)</li>
</ul>
<pre class="brush: python; title: ; notranslate">img = Image.open(in_file).convert(&quot;RGB&quot;)
watermark = Image.new('RGBA', img.size, (0,0,0,0)) </pre>
<p>First, we open the input file and create a watermark image of similar dimensions. Both files need to be in RGB mode since we are working with the alpha channel.</p>
<pre class="brush: python; title: ; notranslate">size = 2
n_font = ImageFont.truetype(FONT, size)
n_width, n_height = n_font.getsize(text)</pre>
<p>Starting with font size 2, we create the text and obtain the width and height of the text.</p>
<pre class="brush: python; title: ; notranslate">while (n_width+n_height &lt; watermark.size[0]):
   size += 2
   n_font = ImageFont.truetype(FONT, size)
   n_width, n_height = n_font.getsize(text)</pre>
<p>By incrementing the font size, we search for a text length that doesn’t exceed the dimension (width) of the image.</p>
<pre class="brush: python; title: ; notranslate">draw = ImageDraw.Draw(watermark, &quot;RGBA&quot;)
 draw.text(((watermark.size[0]-n_width)/2,(watermark.size[1]-n_height)/2),\text, font=n_font)</pre>
<p>With the correct font size, we draw the text onto the center of the watermark image, using the system font declared in the header section.</p>
<pre class="brush: python; title: ; notranslate">watermark = watermark.rotate(angle, Image.BICUBIC)</pre>
<p>We then rotate the image (default is 23 degrees), using Image.BICUBIC approximation.</p>
<pre class="brush: python; title: ; notranslate">alpha = watermark.split()[3]
 alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
 watermark.putalpha(alpha) </pre>
<p>On the alpha channel, we reduce the opacity of the watermark (ie: reduce brightness &amp; contrast) by the default value of 0.25. (Note: value 1 returns the original image).</p>
<pre class="brush: python; title: ; notranslate">Image.composite(watermark, img, watermark).save(out_file, &quot;JPEG&quot;)</pre>
<p>Lastly, we merge the watermark back into the original image and save it as a new JPEG file.</p>
<p>The entire code is as follows:</p>
<pre class="brush: python; title: ; notranslate">from PIL import Image, ImageDraw, ImageFont, ImageEnhance
 import sys
 FONT = &quot;Arial.ttf&quot;
 def add_watermark(in_file, text, out_file=&quot;watermark.jpg&quot;, angle=23, opacity=0.25):
    img = Image.open(in_file).convert(&quot;RGB&quot;)
    watermark = Image.new('RGBA', img.size, (0,0,0,0))
    size = 2
    n_font = ImageFont.truetype(FONT, size)
    n_width, n_height = n_font.getsize(text)
    while (n_width+n_height &lt; watermark.size[0]):
       size += 2
       n_font = ImageFont.truetype(FONT, size)
       n_width, n_height = n_font.getsize(text)
    draw = ImageDraw.Draw(watermark, &quot;RGBA&quot;)
    draw.text(((watermark.size[0]-n_width)/2,(watermark.size[1]-n_height)/2), text, font=n_font)
    watermark = watermark.rotate(angle,Image.BICUBIC)
    alpha = watermark.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    watermark.putalpha(alpha)
    Image.composite(watermark, img, watermark).save(out_file, &quot;JPEG&quot;)
 if __name__ == &quot;__main__&quot;:
    if len(sys.argv) &lt; 3
       sys.exit(&quot;Usage: %s &lt;input-image&gt; &lt;text&gt; &lt;output-image&gt; &lt;angle&gt; &lt;opacity&gt; &quot;
          % os.path.basename(sys.argv[0]))
    add_watermark(*sys.argv[1:])</pre>

<p><a href="http://feedads.g.doubleclick.net/~a/hWkdWgZp028XT8kKGQSqpupuj8k/0/da"><img src="http://feedads.g.doubleclick.net/~a/hWkdWgZp028XT8kKGQSqpupuj8k/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/hWkdWgZp028XT8kKGQSqpupuj8k/1/da"><img src="http://feedads.g.doubleclick.net/~a/hWkdWgZp028XT8kKGQSqpupuj8k/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/IU08VuRG4vI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/adding-watermarks-to-images-watermark-tutorial-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/adding-watermarks-to-images-watermark-tutorial-1/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=adding-watermarks-to-images-watermark-tutorial-1</feedburner:origLink></item>
		<item>
		<title>Setting Up the Python Environment with Virtualenv</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/KnvsTMluDoE/</link>
		<comments>http://pythoncentral.org/setting-up-the-python-environment-with-virtualenv/#comments</comments>
		<pubDate>Sun, 08 Apr 2012 12:46:48 +0000</pubDate>
		<dc:creator>Joanna Alonzo</dc:creator>
				<category><![CDATA[Python Libraries]]></category>
		<category><![CDATA[multiple python environment setup]]></category>
		<category><![CDATA[multiple python versions]]></category>
		<category><![CDATA[python environment]]></category>
		<category><![CDATA[virtualenv]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=277</guid>
		<description><![CDATA[Python is a very powerful scripting language. The language has lots of Python packages you can install and use in your projects. Sometimes, you may have different projects that need different versions of the same package/module. For example, let&#8217;s say you&#8217;re developing a Web application with the latest version of Django for a customer. At<a class="moretag" href="http://pythoncentral.org/setting-up-the-python-environment-with-virtualenv/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>Python is a very powerful scripting language. The language has lots of Python packages you can install and use in your projects. Sometimes, you may have different projects that need different versions of the same package/module. For example, let&#8217;s say you&#8217;re developing a Web application with the latest version of Django for a customer. At the same time, you support some old projects that require Django version 1.0. In that case, you have to change the path that points to Django every time you switch the projects. It would be very handy to have some tools that allows you to switch from one environment to another without affecting each other. That tool is called <strong>virtualenv</strong>.</p>
<p>Virtualenv lets you create virtual Python environments. Everything you install/remove in that environment stays there and other environments are not affected. Most importantly, you don&#8217;t pollute the global package directory of your system. For example, if you want to test an unstable package, virtualenv is the best way to go. If the unstable module you&#8217;re testing have some errors in the installation/uninstallation process, your system will not be affected by it. When you are ready to remove the new unstable module, what you need to do is just removing the virtualenv environment you created.</p>
<p>In this article, we will be using <strong>pip</strong> as the Python Package Manager on a Unix-based Operating System. You can also use <strong>easy_install</strong> if you like. First, let&#8217;s setup up <strong>pip</strong> (You may need to become <strong>root</strong> or use <strong>sudo</strong>):</p>
<pre class="brush: bash; title: ; notranslate">$ easy_install pip</pre>
<p>The next step is to install the virtualenv package :</p>
<pre class="brush: bash; title: ; notranslate">$ pip install virtualenv</pre>
<p>The next step is to create the environment with virtualenv:</p>
<pre class="brush: bash; title: ; notranslate">$ virtualenv --no-site-packages my_blog_env</pre>
<p>With the previous command, we created an isolated Python environment under the directory <strong>my_blog_env</strong>. The option <strong>&#8211;no-site-packages</strong> is telling virtualenv to create for us an empty Python environment. If we didn&#8217;t supply that option, our virtual environment would contain all of the packages in our global Python directory (eg /usr/lib/python2.7). If you need all of your global packages and just want to add a few packages to them, you can ignore that argument and create your environment that way. The next step is to activate your virtual environment:</p>
<pre class="brush: bash; title: ; notranslate">$ cd my_blog_env/
$ source bin/activate</pre>
<p>You should now be seeing that your prompt changed a little bit (refer to parenthesis at the beginning):</p>
<pre class="brush: bash; title: ; notranslate">(my_blog_env)makkalot@makkalot-linux:~/my_blog_env$</pre>
<p>Now you&#8217;re in your virtual environment. If you list the contents of the current directory(virtualenv) you will see 3 directories :</p>
<pre class="brush: bash; title: ; notranslate">$ ls
bin  include  lib</pre>
<p>The “bin” directory includes the executables for our virtualenv environment. That is the place where the Python interpreter is. Also the executables that are installed by some packages will be included in that directory. The “include” directory contains the header files of the environment. Finally, the “lib” directory includes the python files of the installed modules of our virtualenv system.</p>
<p>The next step is to install some packages and use our environment. As we stated in our example let&#8217;s install an old version of Django version 1.0.</p>
<pre class="brush: bash; title: ; notranslate">$ pip install Django==1.0</pre>
<p>Now, we can check if Django is installed in our virtual environment by checking in Python shell.</p>
<pre class="brush: bash; title: ; notranslate">$ python
&gt;&gt;&gt; import django
&gt;&gt;&gt; print django.VERSION
(1, 0, 'final')
&gt;&gt;&gt;
$ deactivate</pre>
<p>Another interesting feature of virtualenv is the ability to create sandboxes for different versions of Python interpreter. With the -p flag you can create environments that use different versions of Python interpreter. Let&#8217;s say for example that you want to create a project with Python&#8217;s latest version 3. To be able to do that, you first need to install the version of Python you want to try on your system. After that, you need to find the path of the executable of the interpreter. You can typically find it under <strong>/usr/bin</strong> (eg: /usr/bin/python3):</p>
<pre class="brush: bash; title: ; notranslate">$ virtualenv --no-site-packages -p /usr/bin/python3 p3_test
 $ cd p3_test
 $ source bin/activate
 $ python
Python 3.2 (r32:88445, Dec  8 2011, 15:26:51)
[GCC 4.5.2] on linux2
Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.
&gt;&gt;&gt; print(&quot;help&quot;)
help</pre>
<p>Now, you are ready to experiment with your new Python 3 environment.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/0cvk-VnqgD7XRGxFMYiDoc6vflM/0/da"><img src="http://feedads.g.doubleclick.net/~a/0cvk-VnqgD7XRGxFMYiDoc6vflM/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/0cvk-VnqgD7XRGxFMYiDoc6vflM/1/da"><img src="http://feedads.g.doubleclick.net/~a/0cvk-VnqgD7XRGxFMYiDoc6vflM/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/KnvsTMluDoE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/setting-up-the-python-environment-with-virtualenv/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/setting-up-the-python-environment-with-virtualenv/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=setting-up-the-python-environment-with-virtualenv</feedburner:origLink></item>
		<item>
		<title>Recursive Directory Traversal in Python: Make a list of your movies!</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/80az-_rH574/</link>
		<comments>http://pythoncentral.org/recursive-directory-traversal-in-python-make-a-list-of-your-movies/#comments</comments>
		<pubDate>Thu, 15 Mar 2012 15:24:15 +0000</pubDate>
		<dc:creator>Jackson</dc:creator>
				<category><![CDATA[Python Recipes]]></category>
		<category><![CDATA[recursive function]]></category>
		<category><![CDATA[recursive programming]]></category>
		<category><![CDATA[traverse directories]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=263</guid>
		<description><![CDATA[What&#8217;s better than making a list of video files in your hard disc drive? Let&#8217;s make a list of all video files in a folder, and all other folders in it. Usage After writing the code, save the file with a .py extension, for example movie_list_maker.py. Then put the file in a directory where you&#8217;ve got movie<a class="moretag" href="http://pythoncentral.org/recursive-directory-traversal-in-python-make-a-list-of-your-movies/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>What&#8217;s better than making a list of video files in your hard disc drive? Let&#8217;s make a list of all video files in a folder, and all other folders in it.</p>
<h2></h2>
<h2 id="section-1">Usage</h2>
<p>After writing the code, save the file with a <strong>.py</strong> extension, for example <strong>movie_list_maker.py</strong>. Then put the file in a directory where you&#8217;ve got movie files (and other files, as well). The code in the script will recursively traverse all other folders within it, and check for video files. If you&#8217;re using Windows and have Python IDLE installed, you can just double-click on the file and check the output. If you&#8217;re on Linux, open a terminal and cd to the directory where your script is, then open the script typing <strong>./movie_list_maker.py</strong> in your terminal (make sure the file is executable first).</p>
<h2 id="section-2">Let&#8217;s Code!</h2>
<p>Let&#8217;s write the code of traversal within a function, which looks like:</p>
<pre class="brush: python; title: ; notranslate">

def processFile(currentDir):
    '''
    Process video files within this directory
    '''
    # Get absolute path of currentDir parameter
    currentDir = os.path.abspath(currentDir)

    # Get a list of files in currentDir
    filesInCurDir = os.listdir(currentDir)

    # Traverse through all files
    for file in filesInCurDir:
        curFile = os.path.join(currentDir, file)

        # Check if normal file/directory
        if os.path.isfile(curFile):

        # Get extention
        curFileExtention = curFile[-3:]

        # Check if file has an extention of typical video files
        if curFileExtention in ['avi', 'dat', 'mp4', 'mkv', 'vob']:

            # We got a video file! Increment counter
            processFile.counter += 1

            # Print it's name
            print '\n%s' % curFile
        else:
            # We got a directory, enter into it for further processing
            processFile(curFile)
</pre>
<p>The code is pretty much self-explanatory along with the comments. This function takes one argument: the name of a directory to work on. Then it gets a list of all files &amp; folders in this directory using the <a title="os.listdir method documentation" href="http://docs.python.org/library/os.html" target="_blank">os.listdir</a> method. We use a for loop to work on the list, check whether the file variable is a normal file or directory using <a title="os.path.isfile documentation" href="http://docs.python.org/library/os.html" target="_blank">os.path.isfile</a> method. If it&#8217;s a normal file, we get the extension of the file using: <strong>curfile[-3:]</strong> &#8211; we assume that last three characters of the filename is it&#8217;s extension, so we&#8217;ve used a negative sign while slicing the <em>curfile</em> variable.</p>
<p>If the filename is a directory other than a regular file, we recursively call the function itself to further process it.</p>
<h2 id="section-3">Call the function&#8230;</h2>
<p>Now, we call this function within the <strong>__main__</strong> scope:</p>
<pre class="brush: python; title: ; notranslate">

if __name__ == '__main__':
    # Get the current working directory
    currentDir = os.getcwd()

    print('Starting processing in %s' % currentDir)

    # Set the number of processed files equal to zero
    processFile.counter = 0

    # Start Processing
    processFile(currentDir)

    # We are done. Exit now.
    print( '\n -- %s Movie File(s) found in directory %s --' % (processFile.counter, currentDir))
    print( '\n Press ENTER to exit!')

    # Wait untile user presses an &lt;enter&gt;
    raw_input()
</pre>
<p>Once again, <a title="os.getwd documentation" href="http://docs.python.org/library/os.html" target="_blank">os.getcwd</a> method helps us to get the current working directory, i.e. the directory where the script resides. It calls our just-written function and also has a counter, it counts how many video files it got. Finally, we print all information we have, and wait for a prompt from user to terminate the program using raw_input method.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/pT5599sKV-SyQdZrL7rWLx3Y2Is/0/da"><img src="http://feedads.g.doubleclick.net/~a/pT5599sKV-SyQdZrL7rWLx3Y2Is/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/pT5599sKV-SyQdZrL7rWLx3Y2Is/1/da"><img src="http://feedads.g.doubleclick.net/~a/pT5599sKV-SyQdZrL7rWLx3Y2Is/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/80az-_rH574" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/recursive-directory-traversal-in-python-make-a-list-of-your-movies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/recursive-directory-traversal-in-python-make-a-list-of-your-movies/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=recursive-directory-traversal-in-python-make-a-list-of-your-movies</feedburner:origLink></item>
		<item>
		<title>Quick Yahoo Finance HTML scraper with BeautifulSoup</title>
		<link>http://feedproxy.google.com/~r/PythonCentral/~3/nAHxvxCMR2Q/</link>
		<comments>http://pythoncentral.org/quick-yahoo-finance-html-scraper-with-beautifulsoup/#comments</comments>
		<pubDate>Thu, 15 Mar 2012 15:02:39 +0000</pubDate>
		<dc:creator>Jackson</dc:creator>
				<category><![CDATA[Python Recipes]]></category>
		<category><![CDATA[beautifulsoup]]></category>
		<category><![CDATA[html searching]]></category>
		<category><![CDATA[scraping]]></category>
		<category><![CDATA[yahoo finance]]></category>

		<guid isPermaLink="false">http://pythoncentral.org/?p=253</guid>
		<description><![CDATA[Python offers a lot of powerful and easy to use tools for automating data collection from the web.  In this example we’ll create a &#8216;web scraper&#8217; to get data from a Yahoo Finance page about stock options. It&#8217;s alright if you don&#8217;t know anything about  stock options, the most important thing is that the website<a class="moretag" href="http://pythoncentral.org/quick-yahoo-finance-html-scraper-with-beautifulsoup/">&#160;&#160;Full Article&#8230;</a>
]]></description>
			<content:encoded><![CDATA[<p>Python offers a lot of powerful and easy to use tools for automating data collection from the web.  In this example we’ll create a &#8216;web scraper&#8217; to get data from a Yahoo Finance page about stock options. It&#8217;s alright if you don&#8217;t know anything about  stock options, the most important thing is that the website has a table of information you can see below that we&#8217;d like to use in our program.  Below is a <a title="Listing for Apple Computer stock options" href="http://finance.yahoo.com/q/op?s=AAPL+Options" target="_blank">listing for Apple Computer stock options</a>.</p>
<p><img class="size-full wp-image-256 aligncenter" title="Apple Computer stock options screenshot" src="http://pythoncentral.org/wp-content/uploads/2012/03/applscreenshot.png" alt="Apple Computer stock options screenshot" width="820" height="360" /></p>
<p>First we need to get the html source for the page . We can do that with urllib, one of the libraries that comes standard with Python.</p>
<pre class="brush: python; title: ; notranslate">

import urllib

optionsUrl = &quot;http://finance.yahoo.com/q/op?s=AAPL+Options&quot;

optionsPage = urllib.urlopen(optionsUrl)&lt;strong&gt;&lt;/strong&gt;
</pre>
<p>This code retrieves the html and returns a file-like object.</p>
<p>If you go to the page we opened with Python and use your browser&#8217;s &#8220;get source&#8221; command you&#8217;ll see that it&#8217;s a large, complicated html file. It will be Python’s job to simplify and extract the useful data using the Beautiful Soup module.  Beautiful Soup is an external module so you&#8217;ll have to install it. If you haven&#8217;t installed Beautiful Soup you can get it <a title="Download Beautiful Soup" href="http://www.crummy.com/software/BeautifulSoup/" target="_blank">here</a>.</p>
<p>The following code will load the page into BeautifulSoup:</p>
<pre class="brush: python; title: ; notranslate">

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(optionsPage)
</pre>
<p>Now we can start trying to extract information. We can see that the options have pretty unique looking names in the &#8220;symbol&#8221; column something like AAPL120127C00505000.  The symbols might be slightly different by the time you read this but we can solve the problem by using Beautiful Soup to search the document for this unique string.</p>
<p>Let&#8217;s search the soup for this particular option (you may have to substitute a different symbol, just get one from the webpage):</p>
<pre class="brush: python; title: ; notranslate">

&gt;&gt;&gt; soup.findAll( text=&quot;AAPL120127C00505000&quot;)

[u'AAPL120127C00505000']
</pre>
<p>This result isn’t very useful yet.  It’s just a unicode string (that&#8217;s what the &#8216;u&#8217; means) of what we searched for.  But Beautiful Soup returns things in a tree format so we can find the context in which this text occurs by asking for it’s &#8216;parent&#8217; node like so:</p>
<pre class="brush: python; title: ; notranslate">

&gt;&gt;&gt; soup.findAll( text=&quot;AAPL120127C00505000&quot;)[0].parent

&lt;a href=&quot;/q?s=AAPL120127C00505000&quot;&gt;AAPL120127C00505000&lt;/a&gt;
</pre>
<p>We don&#8217;t see all the information from the table.  Let&#8217;s try the next higher level.</p>
<pre class="brush: python; title: ; notranslate">

&gt;&gt;&gt; soup.findAll( text=&quot;AAPL120127C00505000&quot;)[0].parent.parent

&lt;td&gt;&lt;a href=&quot;/q?s=AAPL120127C00505000&quot;&gt;AAPL120127C00505000&lt;/a&gt;&lt;/td&gt;
</pre>
<p>And again.</p>
<pre class="brush: python; title: ; notranslate">

&gt;&gt;&gt; soup.findAll( text=&quot;AAPL120127C00505000&quot;)[0].parent.parent.parent
&lt;tr&gt;&lt;td nowrap=&quot;nowrap&quot;&gt;&lt;a href=&quot;/q/op?s=AAPL&amp;amp;k=110.000000&quot;&gt;&lt;strong&gt;110.00&lt;/strong&gt;&lt;/a&gt;&lt;/td&gt;&lt;td&gt;&lt;a href=&quot;/q?s=AAPL120127C00505000&quot;&gt;AAPL120127C00505000&lt;/a&gt;&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;&lt;b&gt;1.25&lt;/b&gt;&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;&lt;span id=&quot;yfs_c63_aapl120127c00505000&quot;&gt; &lt;b style=&quot;color:#000000;&quot;&gt;0.00&lt;/b&gt;&lt;/span&gt;&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;0.90&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;1.05&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;10&lt;/td&gt;&lt;td align=&quot;right&quot;&gt;10&lt;/td&gt;&lt;/tr&gt;
</pre>
<p>Bingo.  It’s still a little messy, but you can see all of the data that we need is there.  If you ignore all the stuff in brackets, you can see that this is just the data from one row.</p>
<pre class="brush: python; title: ; notranslate">

optionsTable = [[x.text for x &lt;strong&gt;in&lt;/strong&gt; y.parent.contents] &lt;strong&gt;for&lt;/strong&gt; y &lt;strong&gt;in&lt;/strong&gt; soup.findAll('td', attrs={&quot;class&quot; : &quot;yfnc_h&quot;, &quot;nowrap&quot; : &quot;nowrap&quot;})]
</pre>
<p>This code is a little dense, so let’s take it apart piece by piece.  The code is a list comprehension within a list comprehension.  Let’s look at the inner one first:</p>
<pre class="brush: python; title: ; notranslate">
for y in soup.findAll('td', attrs={&quot;class&quot; : &quot;yfnc_h&quot;, &quot;nowrap&quot; : &quot;nowrap&quot;})
</pre>
<p>This uses Beautiful Soup’s findAll function to get all of the html elements with a ‘td’ tag and a class of yfnc_h and a nowrap of nowrap.  We chose this because it’s a unique element in every table entry.  If we had just gotten ‘td’s with the class ‘yfnc_h’ we would have gotten seven elements per table entry.  Another thing to note is that we have to wrap the attributes in a dictionary because ‘class’ is one of python’s reserved words.  From the table above it would return this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;td nowrap=&quot;nowrap&quot;&gt;&lt;a href=&quot;/q/op?s=AAPL&amp;amp;k=110.000000&quot;&gt;&lt;strong&gt;110.00&lt;/strong&gt;&lt;/a&gt;&lt;/td&gt;
</pre>
<p>We need to get one level higher and then get the text from all of the child nodes of this node’s parent.  That’s what this code does:</p>
<pre class="brush: python; title: ; notranslate">
[x.text for x in y.parent.contents]
</pre>
<p>This works, but you should be careful if this is code you plan to frequently reuse.  If Yahoo changed the way they format their html, this could stop working.  If you plan to use code like this in an automated way it would be best to wrap it in a <a href="http://docs.python.org/tutorial/errors.html">try</a><a href="http://docs.python.org/tutorial/errors.html">/</a><a title="Python try and catch block - exceptions" href="http://docs.python.org/tutorial/errors.html" target="_blank">catch</a><a href="http://docs.python.org/tutorial/errors.html">block</a> and validate the output.</p>
<p>This should only give you an idea of what you can do with HTML and XML parsing in Python.   You can find the documentation for Beautiful Soup <a title="BeautifulSoup documentation" href="http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html" target="_blank">here</a>.  You’ll find a lot more tools for searching and validating html documents.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/KBW2qjlShZYe0y8v4yZbLe70aJY/0/da"><img src="http://feedads.g.doubleclick.net/~a/KBW2qjlShZYe0y8v4yZbLe70aJY/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/KBW2qjlShZYe0y8v4yZbLe70aJY/1/da"><img src="http://feedads.g.doubleclick.net/~a/KBW2qjlShZYe0y8v4yZbLe70aJY/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/PythonCentral/~4/nAHxvxCMR2Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://pythoncentral.org/quick-yahoo-finance-html-scraper-with-beautifulsoup/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://pythoncentral.org/quick-yahoo-finance-html-scraper-with-beautifulsoup/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=quick-yahoo-finance-html-scraper-with-beautifulsoup</feedburner:origLink></item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using apc
Page Caching using apc
Database Caching using apc
Object Caching 807/990 objects using apc

Served from: pythoncentral.org @ 2012-05-15 22:02:43 -->

