CoCalc Shared Fileswww / wiki / 10(2f)480b(2f)lectures(2f)lec8.html
Author: William A. Stein
10/480b/lectures/lec8
 [top] [TitleIndex] [WordIndex]

# Lecture 8, April 14, 2010

• Several people have asked me about getting tab complete to work in Python. It turns out this is fairly straightforward: I've posted instructions on the webpage.

### Coercion

Now, in that last case, Python was more than willing to turn an integer (like 3) into a string for us (like '3'). In general, Python is more than happy to try converting between common types for you -- all you have to do is ask:

>>> int('3')
3
>>> str(3.14)
'3.14'
>>> int(str(3))
3
>>> str('my house')
'my house'

In general, this is referred to as coercion -- we'll hear about this again when we talk about Sage.

### Other string methods

There are a ton of interesting methods available on strings in Python:

>>> s = "abcdefg"
>>> for method in [ x for x in dir(s) if not x.startswith('_') ]:
...     print method
...
capitalize
center
count
decode
encode
endswith
expandtabs
find
format
index
isalnum
isalpha
isdigit
islower
isspace
istitle
isupper
join
ljust
lower
lstrip
partition
replace
rfind
rindex
rjust
rpartition
rsplit
rstrip
split
splitlines
startswith
strip
swapcase
title
translate
upper
zfill
>>>

You should spend some time reading through what these do. For our purposes, let's mention a few interesting ones:

>>> s = "   this is a STRING\t   abc\t "
>>> s
'   this is a STRING\t   abc\t '
>>> print s
this is a STRING    abc
>>> s.strip()
'this is a STRING\t   abc'
>>> print s.strip()
this is a STRING       abc
>>> s.lstrip()
'this is a STRING\t   abc\t '
>>> s.expandtabs()
'   this is a STRING        abc   '
>>> s.find('STRING')
13
>>> s[s.find('STRING')]
'S'
>>> s[s.find('STRING'):][:6]
'STRING'
>>> t = "string\nwith\nnewlines"
>>> print t
string
with
newlines
>>> print t.replace('\n', ' ')
string with newlines

### Files

Python has excellent support for manipulating files -- there's a lot you can do, but we'll just talk about the basics. You can open files with the open command, which takes an extra argument that tells it whether you want to read or write, and the format you want to read or write in (text or binary):

>>> f = open("test.txt")
['theutaheuththhibyelaterhi\n', 'bye\n', 'later\n', 'asnotehusanotheusnth\n', '3\n']
[]

Notice that the file object "remembers" where it is. That's why the second attempt to read the lines out of the file didn't do anything -- we'd already read them all. One can reset the position, or just close and reopen:

>>> f.seek(0)
['theutaheuththhibyelaterhi\n', 'bye\n', 'later\n', 'asnotehusanotheusnth\n', '3\n']
>>> f = open("test.txt")
['theutaheuththhibyelaterhi\n', 'bye\n', 'later\n', 'asnotehusanotheusnth\n', '3\n']
>>> f.seek(10)
['hthhibyelaterhi\n', 'bye\n', 'later\n', 'asnotehusanotheusnth\n', '3\n']

Now, writing is just as straightforward: there's a write method on file objects, or you can use the "print chevron":

>>> f = open("myfile.html", "w")
>>> print >>f, "<html>"
>>> f.write("<body>this is a short webpage</body>\n")
>>> f.write("</html>\n")
>>> f.close()
['<html>\n', '<body>this is a short webpage</body>\n', '</html>\n']

Note that when you use the write method, you need to specify newlines yourself -- Python won't automatically add them for you. Similarly, if you use print and end the statement with a comma, you won't get a newline added.

There's one basic thing to remember about files: if you're writing to a file, it's possible that the file on disk and the file object in memory are out of sync: Python buffers output. So if you write something, then look at the file, you may notice it's not yet available -- in that case, use the flush method:

>>> f = open("buffering", "w")
>>> f.write('hihihi\n')
['hihihi\n']