Python Cheat Sheet

With thanks to workaround.org for the original.

Strings

Convert to list

"this is a string".split()

Repetition

"string" x 3

Substring

list[3:5]

Formatting

"""this is a %s text""" % ("nice")

Reverse

string[::-1]

Every x'th char

string[::x]

Strip newline

string.strip("\n")

Raw strings

 r“hello world\n“ 

Convert anything into a string

 str(anything) 

Right-pad

 string.rjust(5) 

Left-pad

 string.ljust(5) 

Center string

 string.center(20) 

Length of a string

 len(string) 

Go through the string char-by-char

 for char in string: 

Find a substring

 string.find(mystring, pattern, startpos, endpos) 

import string

Zero-fill a number

 number.zfill(8) 

Lists

Create

 list = [] 

Destroy

 del list 

Fill

 list = [ "a", "b", "mpilgrim" ] 

Append element

list.append(element)

Remove element

list.remove(element)

by element

 del list[3] 

by position

Remove slice

 del list[3:5] 

Append list

 list += [“a“, “b“] 

 list = list1 + list2 

 list.extend(otherlist) 

Insert element

 list.insert(2, 'hello') 

Iterate

for element in list:

Check membership

 if element in list: 

 if list.in("element") 

Get element

 list[5] 

Get slice

 list[3,4,7] 

 list[3:7] 

Get/remove last element

 list.pop() 

Get/remove first element

 list.pop(0) 

Sort

 list.sort() 

<!> returns 'None' - not the list

 list1 = list2.sorted() 

Reverse

 list.reverse() 

Repetition

 [1,2,3] * 2 => [1,2,3,1,2,3] 

Find element

 list.index("example") 

Number of occurences

 list.count('test') 

Join to string

"".join(list)

Split to list list

string.split(“;“)

Create enumeration

range(4)

(gives [0,1,2,3])

range(1,9,3)

(steps... gives [1, 4, 7])

List comprehension

[element*2 for element in list]

Apply function to members

list = map(myfunc, [1, 24, 95])

list = map(myfunc, [1, 2, 3], [4, 5, 6])

(each list delivers one argument for the function)

Return members for which a function gives true

list = filter(myfunc, [1, 3, 4])

Reduce

result = reduce(myfunc, [1, 2, 3]

means: result = foobar(foobar(1, 2), 3) (use the results of the function as the argument of the next call of the function)

Enumerate

enumerate(['a','b','c'])

gives: [[1,'a'], [2,'b'], [3,'c']]

Take an element of each list

for x, y in zip(list1, list2)

Create a named enumeration

 (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) 

Dictionaries

Create

 dict={} 

Fill

 dict = {"server":"mpilgrim", "database":"master"} 

Set element

 dict['a'] = 'b' 

Delete element

 del dict['a'] 

Clear

 dict.clear() 

Get keys

 dict.keys() 

Get values

 dict.values() 

Get key/value tuples

 dict.items() 

Check membership

 dict.has_key('key') 

Get member or zero

 dict.get( "key", 0 ) 

Iterate

 for key, value in dict.iteritems() 

Tuples

Create

 tuple = ("a", "b", "mpilgrim", "z", "example") 

Create with one value

 tuple = (3, ) 

Get element

 tuple[2] 

Get into variables

 x, y, z = tuple 

Misc

Swap values

x,y = y,x

Variables, References, Scopes

Create a reference

 a=[1,2,3] // b=a 

Copy a variable

 a=[1,2,3] // b=a[:] 


Famous quote of the python-list mailing list: You can tell everything is well in the world of dynamic languages when someone posts a question with nuclear flame war potential like "python vs. ruby" and after a while people go off singing hymns about the beauty of Scheme...

PythonCheatSheet (last edited 2008-01-06 23:30:30 by localhost)