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
Conversions
int to char
>>> chr(97)
'a'
char to int
>>> ord('a')
97
int to binary
>>> format(14, 'b')
'1110'
int to hex
>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')
bytes
and int
int
to bytes
>>> d = bytes([65, 66, 67])
>>> d
b'ABC'
bytes
to int
>>> list(b'ABC')
[65, 66, 67]
or
>>> b'ABC'[0]
65
>>> b'ABC'[1]
66
>>> b'ABC'[2]
67
bytes
and hex
Use .fromhex()
and .hex()
>>> hex(ord('A'))
'0x41'
>>> bytes.fromhex('41')
b'A'
>>> bytes.fromhex('41 42')
b'AB'
>>> bytes.fromhex('41 4243')
b'ABC'
>>> bytes.fromhex('414243')
b'ABC'
another example:
>>> str = "89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00"
>>> str
'89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00'
>>> bytes.fromhex(str)
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00'
bytes
to hex
>>> bytes([65, 66, 67])
b'ABC'
>>> bytes([65, 66, 67]).hex()
'414243'
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()