SEESenv/web/html/ch4strings_dicts.html
author amit@thunder
Thu, 25 Feb 2010 00:04:27 +0530
changeset 27 cb14131583c6
parent 25 ed38dd9bdb50
child 28 514098969b11
permissions -rw-r--r--
Started on final changes to the build scripts so that we can start with totally automatic builds

<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>
   Chapter. strings_dicts
  </title>
  <link rel="stylesheet" href="/review/support/styles.css" type="text/css" />
  <meta name="generator" content="DocBook XSL Stylesheets V1.74.3" />
  <link rel="shortcut icon" type="image/png" href="/review/support/figs/favicon.png" />
  <script type="text/javascript" src="/review/support/jquery-min.js">
  </script>
  <script type="text/javascript" src="/review/support/form.js">
  </script>
  <script type="text/javascript" src="/review/support/hsbook.js">
  </script>
 </head>
 <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
  <div class="chapter" id="ch4strings_dicts">
   <div class="titlepage">
   </div>
   <div class="toc">
    <p>
     <b>
      Table of Contents
     </b>
    </p>
    <dl>
     <dt>
      <span class="article">
       <a href="#id2580313">
        Strings
       </a>
      </span>
     </dt>
     <dd>
      <dl>
       <dt>
        <span class="section">
         <a href="#id2578900">
          1. String Formatting
         </a>
        </span>
       </dt>
       <dt>
        <span class="section">
         <a href="#id2631317">
          2. String Methods
         </a>
        </span>
       </dt>
       <dd>
        <dl>
         <dt>
          <span class="section">
           <a href="#id2631332">
            2.1.
            <span class="strong">
             <strong>
              find
             </strong>
            </span>
           </a>
          </span>
         </dt>
         <dt>
          <span class="section">
           <a href="#id2631362">
            2.2.
            <span class="strong">
             <strong>
              join
             </strong>
            </span>
           </a>
          </span>
         </dt>
         <dt>
          <span class="section">
           <a href="#id2631402">
            2.3.
            <span class="strong">
             <strong>
              lower
             </strong>
            </span>
           </a>
          </span>
         </dt>
         <dt>
          <span class="section">
           <a href="#id2631432">
            2.4.
            <span class="strong">
             <strong>
              replace
             </strong>
            </span>
           </a>
          </span>
         </dt>
         <dt>
          <span class="section">
           <a href="#id2631489">
            2.5.
            <span class="strong">
             <strong>
              split
             </strong>
            </span>
           </a>
          </span>
         </dt>
         <dt>
          <span class="section">
           <a href="#id2631548">
            2.6.
            <span class="strong">
             <strong>
              strip
             </strong>
            </span>
           </a>
          </span>
         </dt>
        </dl>
       </dd>
       <dt>
        <span class="section">
         <a href="#id2631592">
          3. Introduction to the standard library
         </a>
        </span>
       </dt>
       <dt>
        <span class="section">
         <a href="#id2631669">
          4. I/O: Reading and Writing Files
         </a>
        </span>
       </dt>
       <dd>
        <dl>
         <dt>
          <span class="section">
           <a href="#id2631699">
            4.1. Opening Files
           </a>
          </span>
         </dt>
         <dt>
          <span class="section">
           <a href="#id2631873">
            4.2. Reading and Writing files
           </a>
          </span>
         </dt>
        </dl>
       </dd>
       <dt>
        <span class="section">
         <a href="#id2632038">
          5. Dictionaries
         </a>
        </span>
       </dt>
       <dd>
        <dl>
         <dt>
          <span class="section">
           <a href="#id2632094">
            5.1.
            <span class="strong">
             <strong>
              dict()
             </strong>
            </span>
           </a>
          </span>
         </dt>
         <dt>
          <span class="section">
           <a href="#id2632158">
            5.2. Dictionary Methods
           </a>
          </span>
         </dt>
        </dl>
       </dd>
      </dl>
     </dd>
    </dl>
   </div>
   <div class="article" title="Strings">
    <div class="titlepage">
     <div>
      <div>
       <h2 class="title">
        <a name="id2580313">
        </a>
        Strings
       </h2>
      </div>
     </div>
     <hr />
    </div>
    <div class="toc">
     <p>
      <b>
       Table of Contents
      </b>
     </p>
     <dl>
      <dt>
       <span class="section">
        <a href="#id2578900">
         1. String Formatting
        </a>
       </span>
      </dt>
      <dt>
       <span class="section">
        <a href="#id2631317">
         2. String Methods
        </a>
       </span>
      </dt>
      <dd>
       <dl>
        <dt>
         <span class="section">
          <a href="#id2631332">
           2.1.
           <span class="strong">
            <strong>
             find
            </strong>
           </span>
          </a>
         </span>
        </dt>
        <dt>
         <span class="section">
          <a href="#id2631362">
           2.2.
           <span class="strong">
            <strong>
             join
            </strong>
           </span>
          </a>
         </span>
        </dt>
        <dt>
         <span class="section">
          <a href="#id2631402">
           2.3.
           <span class="strong">
            <strong>
             lower
            </strong>
           </span>
          </a>
         </span>
        </dt>
        <dt>
         <span class="section">
          <a href="#id2631432">
           2.4.
           <span class="strong">
            <strong>
             replace
            </strong>
           </span>
          </a>
         </span>
        </dt>
        <dt>
         <span class="section">
          <a href="#id2631489">
           2.5.
           <span class="strong">
            <strong>
             split
            </strong>
           </span>
          </a>
         </span>
        </dt>
        <dt>
         <span class="section">
          <a href="#id2631548">
           2.6.
           <span class="strong">
            <strong>
             strip
            </strong>
           </span>
          </a>
         </span>
        </dt>
       </dl>
      </dd>
      <dt>
       <span class="section">
        <a href="#id2631592">
         3. Introduction to the standard library
        </a>
       </span>
      </dt>
      <dt>
       <span class="section">
        <a href="#id2631669">
         4. I/O: Reading and Writing Files
        </a>
       </span>
      </dt>
      <dd>
       <dl>
        <dt>
         <span class="section">
          <a href="#id2631699">
           4.1. Opening Files
          </a>
         </span>
        </dt>
        <dt>
         <span class="section">
          <a href="#id2631873">
           4.2. Reading and Writing files
          </a>
         </span>
        </dt>
       </dl>
      </dd>
      <dt>
       <span class="section">
        <a href="#id2632038">
         5. Dictionaries
        </a>
       </span>
      </dt>
      <dd>
       <dl>
        <dt>
         <span class="section">
          <a href="#id2632094">
           5.1.
           <span class="strong">
            <strong>
             dict()
            </strong>
           </span>
          </a>
         </span>
        </dt>
        <dt>
         <span class="section">
          <a href="#id2632158">
           5.2. Dictionary Methods
          </a>
         </span>
        </dt>
       </dl>
      </dd>
     </dl>
    </div>
    <p id="ch4strings_dicts_1">
     Strings were briefly introduced previously in the introduction document. In this
section strings will be presented in greater detail. All the standard operations
that can be performed on sequences such as indexing, slicing, multiplication, length
minimum and maximum can be performed on string variables as well. One thing to
be noted is that strings are immutable, which means that string variables are
unchangeable. Hence, all item and slice assignments on strings are illegal.
Let us look at a few example.
    </p>
    <pre class="programlisting">
     &gt;&gt;&gt; name = 'PythonFreak'
&gt;&gt;&gt; print name[3]
h
&gt;&gt;&gt; print name[-1]
k
&gt;&gt;&gt; print name[6:]
Freak
&gt;&gt;&gt; name[6:0] = 'Maniac'
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: 'str' object does not support item assignment
    </pre>
    <p id="ch4strings_dicts_2">
     This is quite expected, since string objects are immutable as already mentioned.
The error message is clear in mentioning that 'str' object does not support item
assignment.
    </p>
    <div class="section" title="1.String Formatting">
     <div class="titlepage">
      <div>
       <div>
        <h2 class="title" style="clear: both">
         <a name="id2578900">
         </a>
         1.String Formatting
        </h2>
       </div>
      </div>
     </div>
     <p id="ch4strings_dicts_3">
      String formatting can be performed using the string formatting operator represented
as the percent (%) sign. The string placed before the % sign is formatted with
the value placed to the right of it. Let us look at a simple example.
     </p>
     <pre class="programlisting">
      &gt;&gt;&gt; format = 'Hello %s, from PythonFreak'
&gt;&gt;&gt; str1 = 'world!'
&gt;&gt;&gt; print format % str1
Hello world!, from PythonFreak
     </pre>
     <p id="ch4strings_dicts_4">
      The %s parts of the format string are called the coversion specifiers. The coversion
specifiers mark the places where the formatting has to be performed in a string.
In the example the %s is replaced by the value of str1. More than one value can
also be formatted at a time by specifying the values to be formatted using tuples
and dictionaries (explained in later sections). Let us look at an example.
     </p>
     <pre class="programlisting">
      &gt;&gt;&gt; format = 'Hello %s, from %s'
&gt;&gt;&gt; values = ('world!', 'PythonFreak')
&gt;&gt;&gt; print format % values
Hello world!, from PythonFreak
     </pre>
     <p id="ch4strings_dicts_5">
      In this example it can be observed that the format string contains two conversion
specifiers and they are formatted using the tuple of values as shown.
     </p>
     <p id="ch4strings_dicts_6">
      The s in %s specifies that the value to be replaced is of type string. Values of
other types can be specified as well such as integers and floats. Integers are
specified as %d and floats as %f. The precision with which the integer or the
float values are to be represented can also be specified using a
      <span class="strong">
       <strong>
        .
       </strong>
      </span>
      (
      <span class="strong">
       <strong>
        dot
       </strong>
      </span>
      )
followed by the precision value.
     </p>
    </div>
    <div class="section" title="2.String Methods">
     <div class="titlepage">
      <div>
       <div>
        <h2 class="title" style="clear: both">
         <a name="id2631317">
         </a>
         2.String Methods
        </h2>
       </div>
      </div>
     </div>
     <p id="ch4strings_dicts_7">
      Similar to list methods, strings also have a rich set of methods to perform various
operations on strings. Some of the most important and popular ones are presented
in this section.
     </p>
     <div class="section" title="2.1.find">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2631332">
          </a>
          2.1.
          <span class="strong">
           <strong>
            find
           </strong>
          </span>
         </h3>
        </div>
       </div>
      </div>
      <p id="ch4strings_dicts_8">
       The
       <span class="strong">
        <strong>
         find
        </strong>
       </span>
       method is used to search for a substring within a given string. It
returns the left most index of the first occurence of the substring. If the
substring is not found in the string then it returns -1. Let us look at a few
examples.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; longstring = 'Hello world!, from PythonFreak'
&gt;&gt;&gt; longstring.find('Python')
19
&gt;&gt;&gt; longstring.find('Perl')
-1
      </pre>
     </div>
     <div class="section" title="2.2.join">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2631362">
          </a>
          2.2.
          <span class="strong">
           <strong>
            join
           </strong>
          </span>
         </h3>
        </div>
       </div>
      </div>
      <p id="ch4strings_dicts_9">
       The
       <span class="strong">
        <strong>
         join
        </strong>
       </span>
       method is used to join the elements of a sequence. The sequence
elements that are to be join ed should all be strings. Let us look at a few
examples.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; seq = ['With', 'great', 'power', 'comes', 'great', 'responsibility']
&gt;&gt;&gt; sep = ' '
&gt;&gt;&gt; sep.join(seq)
'With great power comes great responsibility'
&gt;&gt;&gt; sep = ',!'
&gt;&gt;&gt; sep.join(seq)
'With,!great,!power,!comes,!great,!responsibility'
      </pre>
      <p id="ch4strings_dicts_a">
       <span class="emphasis">
        <em>
         Try this yourself
        </em>
       </span>
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; seq = [12,34,56,78]
&gt;&gt;&gt; sep.join(seq)
      </pre>
     </div>
     <div class="section" title="2.3.lower">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2631402">
          </a>
          2.3.
          <span class="strong">
           <strong>
            lower
           </strong>
          </span>
         </h3>
        </div>
       </div>
      </div>
      <p id="ch4strings_dicts_b">
       The
       <span class="strong">
        <strong>
         lower
        </strong>
       </span>
       method, as the name indicates, converts the entire text of a string
to lower case. It is specially useful in cases where the programmers deal with case
insensitive data. Let us look at a few examples.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; sometext = 'Hello world!, from PythonFreak'
&gt;&gt;&gt; sometext.lower()
'hello world!, from pythonfreak'
      </pre>
     </div>
     <div class="section" title="2.4.replace">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2631432">
          </a>
          2.4.
          <span class="strong">
           <strong>
            replace
           </strong>
          </span>
         </h3>
        </div>
       </div>
      </div>
      <p id="ch4strings_dicts_c">
       The
       <span class="strong">
        <strong>
         replace
        </strong>
       </span>
       method replaces a substring with another substring within
a given string and returns the new string. Let us look at an example.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; sometext = 'Concise, precise and criticise is some of the words that end with ise'
&gt;&gt;&gt; sometext.replace('is', 'are')
'Concaree, precaree and criticaree are some of the words that end with aree'
      </pre>
      <p id="ch4strings_dicts_d">
       Observe here that all the occurences of the substring
       <span class="emphasis">
        <em>
         is
        </em>
       </span>
       have been replaced,
even the
       <span class="emphasis">
        <em>
         is
        </em>
       </span>
       in
       <span class="emphasis">
        <em>
         concise
        </em>
       </span>
       ,
       <span class="emphasis">
        <em>
         precise
        </em>
       </span>
       and
       <span class="emphasis">
        <em>
         criticise
        </em>
       </span>
       have been replaced.
      </p>
     </div>
     <div class="section" title="2.5.split">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2631489">
          </a>
          2.5.
          <span class="strong">
           <strong>
            split
           </strong>
          </span>
         </h3>
        </div>
       </div>
      </div>
      <p id="ch4strings_dicts_e">
       The
       <span class="strong">
        <strong>
         split
        </strong>
       </span>
       is one of the very important string methods. split is the opposite of the
       <span class="strong">
        <strong>
         join
        </strong>
       </span>
       method. It is used to split a string based on the argument passed as the
delimiter. It returns a list of strings. By default when no argument is passed it
splits with
       <span class="emphasis">
        <em>
         space
        </em>
       </span>
       (' ') as the delimiter. Let us look at an example.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; grocerylist = 'butter, cucumber, beer(a grocery item??), wheatbread'
&gt;&gt;&gt; grocerylist.split(',')
['butter', ' cucumber', ' beer(a grocery item??)', ' wheatbread']
&gt;&gt;&gt; grocerylist.split()
['butter,', 'cucumber,', 'beer(a', 'grocery', 'item??),', 'wheatbread']
      </pre>
      <p id="ch4strings_dicts_f">
       Observe here that in the second case when the delimiter argument was not set
       <span class="strong">
        <strong>
         split
        </strong>
       </span>
       was done with
       <span class="emphasis">
        <em>
         space
        </em>
       </span>
       as the delimiter.
      </p>
     </div>
     <div class="section" title="2.6.strip">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2631548">
          </a>
          2.6.
          <span class="strong">
           <strong>
            strip
           </strong>
          </span>
         </h3>
        </div>
       </div>
      </div>
      <p id="ch4strings_dicts_10">
       The
       <span class="strong">
        <strong>
         strip
        </strong>
       </span>
       method is used to remove or
       <span class="strong">
        <strong>
         strip
        </strong>
       </span>
       off any whitespaces that exist
to the left and right of a string, but not the whitespaces within a string. Let
us look at an example.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; spacedtext = "               Where's the text??                 "
&gt;&gt;&gt; spacedtext.strip()
"Where's the text??"
      </pre>
      <p id="ch4strings_dicts_11">
       Observe that the whitespaces between the words have not been removed.
      </p>
      <pre class="programlisting">
       Note: Very important thing to note is that all the methods shown above do not
      transform the source string. The source string still remains the same.
      Remember that **strings are immutable**.
      </pre>
     </div>
    </div>
    <div class="section" title="3.Introduction to the standard library">
     <div class="titlepage">
      <div>
       <div>
        <h2 class="title" style="clear: both">
         <a name="id2631592">
         </a>
         3.Introduction to the standard library
        </h2>
       </div>
      </div>
     </div>
     <p id="ch4strings_dicts_12">
      Python is often referred to as a "Batteries included!" language, mainly because
of the Python Standard Library. The Python Standard Library provides an extensive
set of features some of which are available directly for use while some require to
import a few
      <span class="strong">
       <strong>
        modules
       </strong>
      </span>
      . The Standard Library provides various built-in functions
like:
     </p>
     <div class="itemizedlist">
      <ul class="itemizedlist" type="*">
       <li class="listitem" style="list-style-type: *">
        <p id="ch4strings_dicts_13">
         <span class="strong">
          <strong>
           abs()
          </strong>
         </span>
        </p>
       </li>
       <li class="listitem" style="list-style-type: *">
        <p id="ch4strings_dicts_14">
         <span class="strong">
          <strong>
           dict()
          </strong>
         </span>
        </p>
       </li>
       <li class="listitem" style="list-style-type: *">
        <p id="ch4strings_dicts_15">
         <span class="strong">
          <strong>
           enumerate()
          </strong>
         </span>
        </p>
       </li>
      </ul>
     </div>
     <p id="ch4strings_dicts_16">
      The built-in constants like
      <span class="strong">
       <strong>
        True
       </strong>
      </span>
      and
      <span class="strong">
       <strong>
        False
       </strong>
      </span>
      are provided by the Standard Library.
More information about the Python Standard Library is available
     </p>
     <div class="reference">
      <div class="titlepage">
       <hr />
      </div>
      http://docs.python.org/library/
     </div>
    </div>
    <div class="section" title="4.I/O: Reading and Writing Files">
     <div class="titlepage">
      <div>
       <div>
        <h2 class="title" style="clear: both">
         <a name="id2631669">
         </a>
         4.I/O: Reading and Writing Files
        </h2>
       </div>
      </div>
     </div>
     <p id="ch4strings_dicts_17">
      Files are very important aspects when it comes to computing and programming.
Up until now the focus has been on small programs that interacted with users
through
      <span class="strong">
       <strong>
        input()
       </strong>
      </span>
      and
      <span class="strong">
       <strong>
        raw_input()
       </strong>
      </span>
      . Generally, for computational purposes
it becomes necessary to handle files, which are usually large in size as well.
This section focuses on basics of file handling.
     </p>
     <div class="section" title="4.1.Opening Files">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2631699">
          </a>
          4.1.Opening Files
         </h3>
        </div>
       </div>
      </div>
      <p id="ch4strings_dicts_18">
       Files can be opened using the
       <span class="strong">
        <strong>
         open()
        </strong>
       </span>
       method.
       <span class="strong">
        <strong>
         open()
        </strong>
       </span>
       accepts 3 arguments
out of which 2 are optional. Let us look at the syntax of
       <span class="strong">
        <strong>
         open()
        </strong>
       </span>
       :
      </p>
      <p id="ch4strings_dicts_19">
       <span class="emphasis">
        <em>
         f = open( filename, mode, buffering)
        </em>
       </span>
      </p>
      <p id="ch4strings_dicts_1a">
       The
       <span class="emphasis">
        <em>
         filename
        </em>
       </span>
       is a compulsory argument while the
       <span class="emphasis">
        <em>
         mode
        </em>
       </span>
       and
       <span class="emphasis">
        <em>
         buffering
        </em>
       </span>
       are
optional. The
       <span class="emphasis">
        <em>
         filename
        </em>
       </span>
       should be a string and it should be the complete path
to the file to be opened (The path can be absolute or relative). Let us look at
an example.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; f = open ('basic_python/interim_assessment.rst')
      </pre>
      <p id="ch4strings_dicts_1b">
       The
       <span class="emphasis">
        <em>
         mode
        </em>
       </span>
       argument specifies the mode in which the file has to be opened.
The following are the valid mode arguments:
      </p>
      <p id="ch4strings_dicts_1c">
       <span class="strong">
        <strong>
         r
        </strong>
       </span>
       - Read mode
       <span class="strong">
        <strong>
         w
        </strong>
       </span>
       - Write mode
       <span class="strong">
        <strong>
         a
        </strong>
       </span>
       - Append mode
       <span class="strong">
        <strong>
         b
        </strong>
       </span>
       - Binary mode
       <span class="strong">
        <strong>
         +
        </strong>
       </span>
       - Read/Write mode
      </p>
      <p id="ch4strings_dicts_1d">
       The read mode opens the file as a read-only document. The write mode opens the
file in the Write only mode. In the write mode, if the file existed prior to the
opening, the previous contents of the file are erased. The append mode opens the
file in the write mode but the previous contents of the file are not erased and
the current data is appended onto the file.
The binary and the read/write modes are special in the sense that they are added
onto other modes. The read/write mode opens the file in the reading and writing
mode combined. The binary mode can be used to open a files that do not contain
text. Binary files such as images should be opened in the binary mode. Let us look
at a few examples.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; f = open ('basic_python/interim_assessment.rst', 'r')
&gt;&gt;&gt; f = open ('armstrong.py', 'r+')
      </pre>
      <p id="ch4strings_dicts_1e">
       The third argument to the
       <span class="strong">
        <strong>
         open()
        </strong>
       </span>
       method is the
       <span class="emphasis">
        <em>
         buffering
        </em>
       </span>
       argument. This takes
a boolean value,
       <span class="emphasis">
        <em>
         True
        </em>
       </span>
       or
       <span class="emphasis">
        <em>
         1
        </em>
       </span>
       indicates that buffering has to be enabled on the file,
that is the file is loaded on to the main memory and the changes made to the file are
not immediately written to the disk. If the
       <span class="emphasis">
        <em>
         buffering
        </em>
       </span>
       argument is
       <span class="emphasis">
        <em>
         0
        </em>
       </span>
       or
       <span class="emphasis">
        <em>
         False
        </em>
       </span>
       the
changes are directly written on to the disk immediately.
      </p>
     </div>
     <div class="section" title="4.2.Reading and Writing files">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2631873">
          </a>
          4.2.Reading and Writing files
         </h3>
        </div>
       </div>
      </div>
      <div class="section" title="4.2.1.write()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2631882">
           </a>
           4.2.1.
           <span class="strong">
            <strong>
             write()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_1f">
        <span class="strong">
         <strong>
          write()
         </strong>
        </span>
        , evidently, is used to write data onto a file. It takes the data to
be written as the argument. The data can be a string, an integer, a float or any
other datatype. In order to be able to write data onto a file, the file has to
be opened in one of
        <span class="strong">
         <strong>
          w
         </strong>
        </span>
        ,
        <span class="strong">
         <strong>
          a
         </strong>
        </span>
        or
        <span class="strong">
         <strong>
          +
         </strong>
        </span>
        modes.
       </p>
      </div>
      <div class="section" title="4.2.2.read()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2631921">
           </a>
           4.2.2.
           <span class="strong">
            <strong>
             read()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_20">
        <span class="strong">
         <strong>
          read()
         </strong>
        </span>
        is used to read data from a file. It takes the number of bytes of data
to be read as the argument. If nothing is specified by default it reads the entire
contents from the current position to the end of file.
       </p>
       <p id="ch4strings_dicts_21">
        Let us look at a few examples:
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; f = open ('randomtextfile', 'w')
&gt;&gt;&gt; f.write('Hello all, this is PythonFreak. This is a random text file.')
&gt;&gt;&gt; f = open ('../randomtextfile', 'r')
&gt;&gt;&gt; f = open ('../randomtextfile', 'r')
&gt;&gt;&gt; f.read(5)
'Hello'
&gt;&gt;&gt; f.read()
' all, this is PythonFreak. This is a random text file.'
&gt;&gt;&gt; f.close()
       </pre>
      </div>
      <div class="section" title="4.2.3.readline()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2631956">
           </a>
           4.2.3.
           <span class="strong">
            <strong>
             readline()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_22">
        <span class="strong">
         <strong>
          readline()
         </strong>
        </span>
        is used to read a file line by line.
        <span class="strong">
         <strong>
          readline()
         </strong>
        </span>
        reads a line
of a file at a time. When an argument is passed to
        <span class="strong">
         <strong>
          readline()
         </strong>
        </span>
        it reads that
many bytes from the current line.
       </p>
       <p id="ch4strings_dicts_23">
        One other method to read a file line by line is using the
        <span class="strong">
         <strong>
          read()
         </strong>
        </span>
        and the
        <span class="strong">
         <strong>
          for
         </strong>
        </span>
        construct. Let us look at this block of code as an example.
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; f = open('../randomtextfile', 'r')
&gt;&gt;&gt; for line in f:
...     print line
...
Hello all!

This is PythonFreak on the second line.

This is a random text file on line 3
       </pre>
      </div>
      <div class="section" title="4.2.4.close()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2632015">
           </a>
           4.2.4.
           <span class="strong">
            <strong>
             close()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_24">
        One must always close all the files that have been opened. Although, files opened
will be closed automatically when the program ends. When files opened in read mode
are not closed it might lead to uselessly locked sometimes. In case of files
opened in the write mode it is more important to close the files. This is because,
Python maybe using the file in the buffering mode and when the file is not closed
the buffer maybe lost completely and the changes made to the file are lost forever.
       </p>
      </div>
     </div>
    </div>
    <div class="section" title="5.Dictionaries">
     <div class="titlepage">
      <div>
       <div>
        <h2 class="title" style="clear: both">
         <a name="id2632038">
         </a>
         5.Dictionaries
        </h2>
       </div>
      </div>
     </div>
     <p id="ch4strings_dicts_25">
      A dictionary in general, are designed to be able to look up meanings of words.
Similarly, the Python dictionaries are also designed to look up for a specific
key and retrieve the corresponding value. Dictionaries are data structures that
provide key-value mappings. Dictionaries are similar to lists except that instead
of the values having integer indexes, dictionaries have keys or strings as indexes.
Let us look at an example of how to define dictionaries.
     </p>
     <pre class="programlisting">
      &gt;&gt;&gt; dct = { 'Sachin': 'Tendulkar', 'Rahul': 'Dravid', 'Anil': 'Kumble'}
     </pre>
     <p id="ch4strings_dicts_26">
      The dictionary consists of pairs of strings, which are called
      <span class="emphasis">
       <em>
        keys
       </em>
      </span>
      and their
corresponding
      <span class="emphasis">
       <em>
        values
       </em>
      </span>
      separated by
      <span class="emphasis">
       <em>
        :
       </em>
      </span>
      and each of these
      <span class="emphasis">
       <em>
        key-value
       </em>
      </span>
      pairs are
comma(',') separated and the entire structure wrapped in a pair curly braces
      <span class="emphasis">
       <em>
        {}
       </em>
      </span>
      .
     </p>
     <pre class="programlisting">
      Note: The data inside a dictionary is not ordered. The order in which you enter
the key-value pairs is not the order in which they are stored in the dictionary.
Python has an internal storage mechanism for that which is out of the purview
of this document.
     </pre>
     <div class="section" title="5.1.dict()">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2632094">
          </a>
          5.1.
          <span class="strong">
           <strong>
            dict()
           </strong>
          </span>
         </h3>
        </div>
       </div>
      </div>
      <p id="ch4strings_dicts_27">
       The
       <span class="strong">
        <strong>
         dict()
        </strong>
       </span>
       function is used to create dictionaries from other mappings or other
dictionaries. Let us look at an example.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; diction = dict(mat = 133, avg = 52.53)
      </pre>
      <p id="ch4strings_dicts_28">
       <span class="strong">
        <strong>
         String Formatting with Dictionaries:
        </strong>
       </span>
      </p>
      <p id="ch4strings_dicts_29">
       String formatting was discussed in the previous section and it was mentioned that
dictionaries can also be used for formatting more than one value. This section
focuses on the formatting of strings using dictionaries. String formatting using
dictionaries is more appealing than doing the same with tuples. Here the
       <span class="emphasis">
        <em>
         keyword
        </em>
       </span>
       can be used as a place holder and the
       <span class="emphasis">
        <em>
         value
        </em>
       </span>
       corresponding to it is replaced in
the formatted string. Let us look at an example.
      </p>
      <pre class="programlisting">
       &gt;&gt;&gt; player = { 'Name':'Rahul Dravid', 'Matches':133, 'Avg':52.53, '100s':26 }
&gt;&gt;&gt; strng = '%(Name)s has played %(Matches)d with an average of %(Avg).2f and has %(100s)d hundreds to his name.'
&gt;&gt;&gt; print strng % player
Rahul Dravid has played 133 with an average of 52.53 and has 26 hundreds to his name.
      </pre>
     </div>
     <div class="section" title="5.2.Dictionary Methods">
      <div class="titlepage">
       <div>
        <div>
         <h3 class="title">
          <a name="id2632158">
          </a>
          5.2.Dictionary Methods
         </h3>
        </div>
       </div>
      </div>
      <div class="section" title="5.2.1.clear()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2632167">
           </a>
           5.2.1.
           <span class="strong">
            <strong>
             clear()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_2a">
        The
        <span class="strong">
         <strong>
          clear()
         </strong>
        </span>
        method removes all the existing
        <span class="emphasis">
         <em>
          key-value
         </em>
        </span>
        pairs from a dictionary.
It returns
        <span class="emphasis">
         <em>
          None
         </em>
        </span>
        or rather does not return anything. It is a method that changes
the object. It has to be noted here that dictionaries are not immutable. Let us
look at an example.
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; dct
{'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
&gt;&gt;&gt; dct.clear()
&gt;&gt;&gt; dct
{}
       </pre>
      </div>
      <div class="section" title="5.2.2.copy()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2632202">
           </a>
           5.2.2.
           <span class="strong">
            <strong>
             copy()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_2b">
        The
        <span class="strong">
         <strong>
          copy()
         </strong>
        </span>
        returns a copy of a given dictionary. Let us look at an example.
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; dct = {'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
&gt;&gt;&gt; dctcopy = dct.copy()
&gt;&gt;&gt; dctcopy
{'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
       </pre>
      </div>
      <div class="section" title="5.2.3.get()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2632233">
           </a>
           5.2.3.
           <span class="strong">
            <strong>
             get()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_2c">
        <span class="strong">
         <strong>
          get()
         </strong>
        </span>
        returns the
        <span class="emphasis">
         <em>
          value
         </em>
        </span>
        for the
        <span class="emphasis">
         <em>
          key
         </em>
        </span>
        passed as the argument and if the
        <span class="emphasis">
         <em>
          key
         </em>
        </span>
        does not exist in the dictionary, it returns
        <span class="emphasis">
         <em>
          None
         </em>
        </span>
        . Let us look at an
example.
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; print dctcopy.get('Saurav')
None
&gt;&gt;&gt; print dctcopy.get('Anil')
Kumble
       </pre>
      </div>
      <div class="section" title="5.2.4.has_key()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2632271">
           </a>
           5.2.4.
           <span class="strong">
            <strong>
             has_key()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_2d">
        This method returns
        <span class="emphasis">
         <em>
          True
         </em>
        </span>
        if the given
        <span class="emphasis">
         <em>
          key
         </em>
        </span>
        is in the dictionary, else it returns
        <span class="emphasis">
         <em>
          False
         </em>
        </span>
        .
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; dctcopy.has_key('Saurav')
False
&gt;&gt;&gt; dctcopy.has_key('Sachin')
True
       </pre>
      </div>
      <div class="section" title="5.2.5.pop()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2632301">
           </a>
           5.2.5.
           <span class="strong">
            <strong>
             pop()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_2e">
        This method is used to retrieve the
        <span class="emphasis">
         <em>
          value
         </em>
        </span>
        of a given
        <span class="emphasis">
         <em>
          key
         </em>
        </span>
        and subsequently
remove the
        <span class="emphasis">
         <em>
          key-value
         </em>
        </span>
        pair from the dictionary. Let us look at an example.
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; print dctcopy.pop('Sachin')
Tendulkar
&gt;&gt;&gt; dctcopy
{'Anil': 'Kumble', 'Rahul': 'Dravid'}
       </pre>
      </div>
      <div class="section" title="5.2.6.popitem()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2632335">
           </a>
           5.2.6.
           <span class="strong">
            <strong>
             popitem()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_2f">
        This method randomly pops a
        <span class="emphasis">
         <em>
          key-value
         </em>
        </span>
        pair from a dictionary and returns it.
The
        <span class="emphasis">
         <em>
          key-value
         </em>
        </span>
        pair returned is removed from the dictionary. Let us look at an
example.
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; print dctcopy.popitem()
('Anil', 'Kumble')
&gt;&gt;&gt; dctcopy
{'Rahul': 'Dravid'}

Note that the item chosen is completely random since dictionaries are unordered
as mentioned earlier.
       </pre>
      </div>
      <div class="section" title="5.2.7.update()">
       <div class="titlepage">
        <div>
         <div>
          <h4 class="title">
           <a name="id2632371">
           </a>
           5.2.7.
           <span class="strong">
            <strong>
             update()
            </strong>
           </span>
          </h4>
         </div>
        </div>
       </div>
       <p id="ch4strings_dicts_30">
        The
        <span class="strong">
         <strong>
          update()
         </strong>
        </span>
        method updates the contents of one dictionary with the contents
of another dictionary. For items with existing
        <span class="emphasis">
         <em>
          keys
         </em>
        </span>
        their
        <span class="emphasis">
         <em>
          values
         </em>
        </span>
        are updated,
and the rest of the items are added. Let us look at an example.
       </p>
       <pre class="programlisting">
        &gt;&gt;&gt; dctcopy.update(dct)
&gt;&gt;&gt; dct
{'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
&gt;&gt;&gt; dctcopy
{'Anil': 'Kumble', 'Sachin': 'Tendulkar', 'Rahul': 'Dravid'}
       </pre>
      </div>
     </div>
    </div>
   </div>
  </div>
 </body>
</html>