- str() repr()
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'
write a table
>>> for x in range(1,11):
... print repr(x).rjust(2),
... print repr(x*x).rjust(3),
... print repr(x*x*x).rjust(4)
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
write a table 2.0
1 >>> for x in range(1,11):
2 ... print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
3 ...
4 1 1 1
5 2 4 8
6 3 9 27
7 4 16 64
8 5 25 125
9 6 36 216
10 7 49 343
11 8 64 512
12 9 81 729
13 10 100 1000
zfill
>>> 'hello'.zfill(10)
'00000hello'
>>> '12.3'.zfill(7)
'00012.3'
str.format()
>>> print "hello {}".format("york")
hello york
>>> print "{1} {0}!".format("york","hello")
hello york!
>>> print "{greeting} {people}".format(greeting="good morning",people="york")
good morning york
'!r'
>>> import math
>>> print 'The value of PI is approximately {}.'.format(math.pi)
The value of PI is approximately 3.14159265359.
>>> print 'The value of PI is approximately {!r}.'.format(math.pi)
The value of PI is approximately 3.141592653589793.
>>> import math
>>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
The value of PI is approximately 3.142.
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print '{0:10} ==> {1:10d}'.format(name, phone)
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
Open files
open(filename, mode)
'r' only be read,
'w' only writing,
'a' for appending,
'r+' both reading and writing,
'r' will be assumed if it’s omitted.
file:read() f.read(size), size is optional, return string.caution!: it’s your problem if the file is twice as large as your machine’s memory
>>> f = open("hello.txt")
>>> f.read()
'hello world!\nsecond line!\nthird line!\n'
file:readline()
>>> f = open("hello.txt")
>>> f.readline()
'hello world!\n'
>>> f.readline()
'second line!\n'
>>> f.readline()
'third line!\n'
>>> f.readline()
''
>>> f.readline()
''
f.readlines()
>>> f.readlines()
['hello world!\n', 'second line!\n', 'third line!\n']
another way to process each line in the file
>>> f = open("hello.txt")
>>> for line in f:
... print line
...
hello world!
second line!
third line!
f.write()
>>> f = open("hello.txt","a")
>>> f.write("this is forth lien\n")
f.tell(), f.seek(position)
>>> f.seek(0)
>>> f.read(1)
'h'
>>> f.tell()
1L
Pickle:read/write some abstract object
pickle.dump(x, f)
x = pickle.load(f)