12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

9. Immutable types. Either of the following solutions works. Index assignmentdoesn’t, because strings are immutable:>>> S = "spam">>> S = S[0] + 'l' + S[2:]>>> S'slam'>>> S = S[0] + 'l' + S[2] + S[3]>>> S'slam'10. Nesting. Here is a sample:>>> me = {'name':('mark', 'e', 'lutz'), 'age':'?', 'job':'engineer'}>>> me['job']'engineer'>>> me['name'][2]'lutz'11. Files. Here’s one way to create and read back a text file in <strong>Python</strong> (ls is a Unixcommand; use dir on Windows):# File: maker.pyfile = open('myfile.txt', 'w')file.write('Hello file world!\n') # Or: open( ).write( )file.close( )# close not always needed# File: reader.pyfile = open('myfile.txt')# 'r' is default open modeprint file.read() # Or print open( ).read( )% python maker.py% python reader.pyHello file world!% ls -l myfile.txt-rwxrwxrwa 1 0 0 19 Apr 13 16:33 myfile.txt12. The dir function revisited. The following is what you get for lists; dictionaries dothe same, with different method names. Note that the dir result expanded in<strong>Python</strong> 2.2—you’ll see a large set of additional underscore names that implementexpression operators and support the subclassing in Part VI. The _ _methods_ _attribute disappeared in 2.2 as well because it wasn’t consistently implemented—use dir to fetch attribute lists today instead:>>> []._ _methods_ _['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort',...]>>> dir([])['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort',...]Part II, Types and Operations | 653

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!