Black Mamba

Faster, Higher, Stronger.

Python Notes IV

input() and raw_input()

  • input(): Gets inputs from the user
1
2
3
input("Enter a number: ")
Enter a number: 3
3
  • raw_input(): Gets input from the user, as a string
1
2
3
raw_input("Enter a number: ")
Enter a number: 3
'3'

repr() and str()

  • repr(): Returns a string representation of a value
  • A synonym for repr(‘x’) is ‘x’
1
2
3
4
print repr("Hello, world!")
'Hello, world!'
print repr(10000L)
10000L
  • str(): Converts a value to a string
1
2
3
4
print str("Hello, world!")
Hello, world!
print str(10000L)
10000

Slicing

  • numbers[beg : end : direction(interval)]
  • range(beg…<end), i.e., [beg, end)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers[3:6] = [4, 5, 6]
numbers[-3:-1] = [8, 9]
numbers[-3:] = [8, 9, 10]
numbers[:3] = [1, 2, 3]

numbers[0:10:2] = [1, 3, 5, 7, 9]
numbers[3:6:2] = [4, 6]

numbers[::3] = [1, 4, 7, 10]
numbers[8:3] = []
numbers[8:3:-1] = [9, 8, 7, 6, 5]

numbers[10:0:-2] = [10, 8, 6, 4, 2]
numbers[5::-2] = [6, 4, 2]
numbers[:5:-2] = [10, 8]

numbers[5::-2] = [6, 4, 2]
numbers[:5:-1] = [10, 9, 8, 7]

Membership

  • if … in …
  • if … not in …

Lists

  • To convert a list of characters such as the preceding code back to a string, use ‘ ’.join(somelist)
1
2
3
4
somelist = ['b', 'o', 'y']
' '.join(somelist)

'boy'
  • Deleting Elements use del
1
2
3
4
5
names = ['Ada', 'Bob', 'Cecil', 'David']
del names[2]

names
['Ada', 'Bob', 'David']
  • Assigning to Slices
1
2
3
4
5
name = list('Perl')
name[1:] = list('ython')

name
['P', 'y', 't', 'h', 'o', 'n']
  • Slice assignments can be used to insert elements without replacing any of the original ones
1
2
3
4
5
6
7
8
nums = [1, 5]
nums[1:1] = [2, 3, 4]
nums
[1, 2, 3, 4, 5]

nums[1:4] = []  # del nums[1:4]
nums
[1, 5]
  • String Formatting
1
2
3
4
5
6
7
8
9
str = "Hello, %s! %s are you?"
val = ('Peter', 'How')
print (str % val)

Hello, Peter! How are you?

# for short
'%s + %s = %s' % (1, 1, 2)
'1 + 1 = 2'
  • Template Strings
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from string import Template

s = Template('$x,  glorious $x!')
s.substitute(x = 'slurm')
'slurm,  glorious slurm!'

# the replacement is part of a word
s = Template("It's ${x}tastic!")
s.substitute(x = ' slurm')
"It's  slurmtastic!"

# insert a dollar sign, use $$
s = Template("Make $$ selling $x!")
s.substitute(x='slurm')
'Make $ selling slurm!'

# supply the value-name pairs in a dictionary
s = Template('A $thing must never $action.')
d = {}
d['thing'] = 'dog'
d['action'] = 'eat grass'
s.substitute(d)
'A dog must never eat grass.'
  • find()
1
2
3
title = "Monty Python's Flying Circus"
title.find('Python')
6
  • split()
1
2
3
4
5
6
7
8
'1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']

'/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

'a    aa    aaa    '.split()
['a', 'aa', 'aaa']
  • join() The inverse of split, used to join the elements of a sequence
1
2
3
4
5
6
7
8
9
10
11
12
13
seq = ['1', '2', '3', '4', '5']
'+'.join(seq)
'1+2+3+4+5'

dirs = '', 'usr', 'bin', 'env'
dirs
('', 'usr', 'bin', 'env')

'/'.join(dirs)
'/usr/bin/env'

print('C:' + '\\'.join(dirs))
C:\usr\bin\env
  • strip() Get rid of the characters listed in strip()
1
2
3
4
5
6
7
8
9
'!!!   a    aa    aaa    !!!!!'.strip('!')
'   a    aa    aaa    '

'   a    aa    aaa    '.strip()
'a    aa    aaa'

# list all that to remove
'*** SPAN * for * everyone!!! ***'.strip(' *!')
'SPAN * for * everyone'
  • title()
1
2
"that's all, folks".title()
"That'S All, Folks"
  • string.capwords()
1
2
3
import string
string.capwords("that's all, folks")
"That's All, Folks"
  • replace()
1
2
'This is a cat.'.replace('cat', 'dog')
'This is a dog.'
  • maketrans() and translate()
1
2
3
4
5
6
from string import maketrans

trantab = maketrans('aeiou', '12345')  # (in -> out)
"this is string example...wow!".translate(trantab);

'th3s 3s 1 str3ng 2x1mpl2...w4w!'
  • An optional second argument can be supplied to specify that should be deleted
1
2
3
4
5
'this is an incredible test..'.translate(trantab)
'th3s 3s 1n 3ncr2d3bl2 t2st.'

'this is an incredible test'.translate(trantab, ' ')
'th3s3s1n3ncr2d3bl2t2st'

Dictionary

  • dict()
1
2
3
# (key, value)
dict(name = 'Peter', age = 12)
{'name': 'Peter', 'age': 12}
  • clear()
1
2
3
4
5
6
7
8
9
10
11
x = {}
y = x   # refer to the same dictionary
x['key'] = 'value'

y
{'key': 'value'}

x.clear()

y   # y is also empty
{}
  • copy()
1
2
3
4
5
6
7
8
9
x = {'username': 'admin', 'machines': ['foo', 'bar']}
y = x.copy()
y['username'] = 'peter'
y['machines'].remove('bar')

y
{'username': 'peter', 'machines': ['foo']}
x
{'username': 'admin', 'machines': ['foo']}
  • deepcopy() Avoid the situation that modify the value.
1
2
3
4
5
6
7
8
9
10
11
12
13
d = {}
d['names'] = ['Alfred', 'Bertrand']

c = d.copy()
deepc = deepcopy(d)
d['names'].append('Clive')

d
{'names': ['Alfred', 'Bertrand', 'Clive']}
c
{'names': ['Alfred', 'Bertrand', 'Clive']}
deepc
{'names': ['Alfred', 'Bertrand']}
  • fromkeys Create a new dictionary with the given keys.
1
2
3
4
5
6
7
8
{}.fromkeys(['name', 'age'])
{'name': None, 'age': None}

dict.fromkeys(['name', 'age'])
{'name': None, 'age': None}

dict.fromkeys(['name', 'age'], '(default)')
{'name': '(default)', 'age': '(default)'}
  • get()
1
2
3
4
5
6
7
d = {}
d['name'] = 'Peter'
d['addr'] = 'England'
d.get('name')
'Peter'
d.get('addr')
'England'
  • has_key() Check whether a dictionary has a given key.
1
2
3
4
5
6
7
# Be gone after Python 3.0
d = {}
d.has_key('name')
False
d['name'] = 'Peter'
d.has_key('name')
True
  • items() Return all the items of dictionary as a list of the form (key, value)
1
2
3
d = {'title': 'Python Web Site', 'url': 'http:#www.python.org', 'spam': 0}
d.items()
[('url', 'http:#www.python.org'), ('spam', 0), ('title', 'Python Web Site')]
  • iteritems()
1
2
3
4
5
6
Return an iterator instead of a list
it = d.iteritems()
it
`dictionary-itemiterator object at 0x10b918788`
list(it)
[('url', 'http:#www.python.org'), ('spam', 0), ('title', 'Python Web Site')]
  • pop()
1
2
3
4
5
6
7
d = {'spam': 0, 'url': 'http:#www.python.org', 'title': 'Python Web Site'}

d.pop('spam')
0

d
{'url': 'http:#www.python.org', 'title': 'Python Web Site'}
  • popitem()
1
2
3
4
5
d = {'url': 'http:#www.python.org', 'title': 'Python Web Site'}
d.popitem()
('url', 'http:#www.python.org')
d
{'title': 'Python Web Site'}
  • setdefault() Set the value corresponding to the given key if it not already in the dictionary
1
2
3
4
5
d = {}
d.setdefault('name', 'N/A')
'N/A'
d
{'name': 'N/A'}
  • update()
1
2
3
4
5
6
7
8
9
d = {
'name': 'Peter',
'addr': 'England',
}
x = {'addr': 'France'}
d.update(x)

d
{'name': 'Peter', 'addr': 'France'}
  • values
1
2
3
4
5
6
d = {}
d[1] = 1
d[2] = 2

d.values()
dict_values([1, 2])
  • range(a, b), [a, b)
1
2
3
4
5
for i in range(10, 12):
print(i)

10
11

Importing

  • import sth. from a module
1
2
3
from somemodule import somefunction
or
from somemodule import *
  • Define aliases
1
2
3
from math import sqrt as foo
foo(4)
2.0
  • loop the key of a dictionary
1
2
3
4
5
6
7
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, d[key])

# this one is better
for key, value in d.items():
print(key, value)
  • Slightly Loopy
1
2
[x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
1
2
3
4
5
6
7
8
res = []
for x in range(3):
for y in range(3):
res.append((x, y))

# for short
[(x, y) for x in range(2) for y in range(2)]
[(0, 0), (0, 1), (1, 0), (1, 1)]

Executing and Evaluating

  • exec
1
2
exec "print 'hello, world!'"
hello, world!
  • eval
1
2
3
4
d = {}
d['x'] = 3  # exec 'x = 3' in d
eval('x * x', d)
9

Bonus: Trick of Reduce Code

  • Comparison
1
2
3
# using the former instead of the latter
1 < num < 10
1 < num and num < 10
  • or
1
2
3
4
5
name = input('Enter name: ') or 'N/A'
Enter name:

name
'N/A'
  • a if b else c
1
2
3
4
5
score = int(99)
grade = 'A' if 90 <= score <= 100 else 'B'

grade
'A'