logo

Python Cheatsheet

String

# Prefix
>>> 'asdf'.startswith('as')
True

# Trim whitespaces
>>> ' asdf '.strip()
'asdf'

# Split string
>>> "a b c".split()
['a', 'b', 'c']

# Repeated characters
>>> 'a' * 10
'aaaaaaaaaa'

# Format
>>> "hello {}".format("world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'

List

>>> [[0] * 4] * 4
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Repeated Values In List/Tuple

List

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Tuple.

>>> (0,) * 10
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

Notice the comma in (0,), otherwise it is scalar calculation

>>> (1) * 10
10

Init 2D array

>>> a = [[0] * 3 for _ in range(4)]
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

2D 8-Directions

>>> [(x, y) for x in d for y in d if x != 0 or y != 0]
[(1, 1), (1, 0), (1, -1), (0, 1), (0, -1), (-1, 1), (-1, 0), (-1, -1)]
# Append to list
list.append()

# contains
>>> a = [1, 2, 3]
>>> 1 in a
True
>>> 4 in a
False

# map
map(lambda x: x * 2, [1, 2, 3])

# length
len([1,2,3])

# join
>>> "|".join(["a", "b", "c"])
'a|b|c'

# Deconstruct
>>> a, *b, c = [1, 2, 3, 4, 5, 6]
>>> a
1
>>> b
[2, 3, 4, 5]
>>> c
6

Download pages from wikipedia

import urllib.request
opener = urllib.request.build_opener()
opener.addheaders =[('User-agent','Mozilla/5.0')]
infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes')
page = infile.read()