Common Python stuff with syntax.
Python: Remember uses American English, not normal English
Importing Libraries
import thing to import here
Eg:
import math
Input
Input with type interpretation:
variable = input("Prompt for input")
Input to string:
variable = raw_input("Prompt for input")
Type conversion
To integer:
int("string")
To string:
str(12)
String to list (each letter):
list(string)
String to list (each word):
string.split(' ')
List to string:
''.join(list)
where '' contains the separator.
Strings & lists
Many operations on the two types are the same. If our example string is called "string", and our example list is called "list":
Concatenation
uses + for both types, but must be same type being concatenated.
Length
len(string)
or
len(list)
len(something) will return value equal to the last index + 1
Letters in string
Letter n in string "string" is represented by:
"string"[n-1]
Last letter in string:
"string"[-1]
Show letters from letter 3 to 7 (indexes 2 to 6)
"string"[2:7]
Letters up to & including letter 8 (indexes to 7)
"string"[:8]
Letters after letter 2 (indexes from 1)
"string"[2:]
Reverse string order
string[::-1]
Change case
string.lower() string.upper()
Replace
In string:
string.replace(oldSubString, newSubString)
Append item to list
list.append(newItem)
Sort
list.sort()
Strip whitespace
Both sides:
string.strip()
Just from left:
string.lstrip()
Just from right:
string.rstrip()
Find in string
String at the beginning:
string.startswith(subString)
String at end:
string.endswith(subString)
Formatting strings
In general, shown as the following:
print "%d is %s" % (123, "good")
Kinds of formatting:
%s -- string %d -- display number %10d -- display number within field of 10 characters (rightmost side) %f -- floating point numbers (default field 8 digits long) %5.3f -- float in field of 5 with precision 3 %-5.3f -- same as above, but left adjusted %+5.3f -- same as two above, but includes sign
Values taken from tuple in same order.
Dictionaries
Enclosed in curly braces as follows:
myDictionary = {'dog':1, 'cat':0, 'sister':'annoying little twerp'}
Call with key values:
myDictionary['dog']
will return
1
Keys
List of keys:
dictionary.keys()
Number of keys:
len(dictionary.keys())
Other
Check for existence of key (returns Boolean):
dictionary.has_key(key)
Remove and return item:
dictionary.pop(key)
Tuples
Immutable lists displayed with round rather than square brackets.
Boolean
Comparisons
==
equality
!=
inequality
> >=
Greter than/ greater than or equals to
< <=
Less than/ less than or equals to
Range:
range(0,10,2)
counts from 0 to ten (not inclusive of 10) in steps of 2.
And & or are litterally written as
and
&
or
Files
Open a file:
f = open('file.extension', 'rU')
Read next line:
f.readline()
Read all lines (list with one item per line):
f.readlines()
Note: will probably contain trailing \n.
Close file:
f.close()
Functions
Define a function:
def hello(name): Stuff goes here
Call a function:
hello(args)
A function with named parameters with default values:
def foo(x=1, y=9, z=6): print x, y, z foo(z=1,x=2) # => 2 9 1
Can use an asterisk to parse in arguments as a list.
Can use two asterisks to parse in arguments as a dictionary:
def bar(**params): print params
bar('p'=1, 'q'=2)
returns {'p':1, 'q':2}
Handy for loops
Access one line of a file at a time:
for line in f.readlines(): Stuff goes here
Cycle through the key/value pairs in a dictionary:
for key, value in dictionary.iteritems(): Stuff goes here
(Also iterkeys and itervalues to iterate over only one or the other)
Testing
import doctest def function(variables): """This is some documentaion Here are some test cases: >>> function(1) expectedResult >>> function(2) anotherExpectedResult """ doctest.testmod()