Essential Python
Cheat Sheet By Techie Programmer
Data Types Comparison Operators More String Operations Environment Co e Snippets
d
Integer - 123
x< y Less x <= y Less or eq
s.lower() - lowercase copy of s
sys.argv - List of command line arguments
Loop Over Sequence
float - 3.12
x > y Greater x >= y Greater or eq
s.replace(old, new) - copy of s with
(argv[0] is executable)
for index, value in enumerate(se ):
q
string - “techie”, ‘programmer’
x == y E ual x = y ot e ual
q ! N q old replaced with new
print( {} : {} .format(index, value)
" " )
Boolean - True , False
s.split( delim ) - list of substrings
os.environ - Dictionary of environment
List - [ values... ]
delimited by delimal
variables
Loop Over Dictionary
Dictionary - {key:value ,...}
s.strip() - copy of s with
for key in sorted(dict):
Boolean Operators print(dict[key]
set - {value1, value2,...} whitespace trimmed
os.curdir - tring with path of current
S
)
not x x and y x or y s.upper() - uppercase copy of s
directory
Read a File
Statements See also http://docs.python.org/library/ import sys; print(sys.argv) or
with open( lename , r ) as f
"fi " " " :
If Statement
stdtypes.html stringmethods
# from sys import argv; print(argv) for line in f: line = line.rstrip( n )
"\ "
if expression :
Exception Han ling d trip newline
#S
statements
try:
print(line)
elif expression statements
Mutating List Operations
:
String ormatting
F
statements
except [ exception type [ asvar ] ]:
del lst[i] - Deletes ith item from lst
else:
statements
" Hello, {0} {1}".format("abe", "jones")
h i, nilesh ha algi d Here !
slst.append(e) - Appends e to lst
statements
nally
fi Hello, abe jones
A AT
K echie P rogramer
lst.insert(i, e) - Inserts e before ith item in
: statements for more such content join my handels
lst
While Loop
" Hello, {fn} {ln}".format(fn="abe", ln="jones")
lst.sort() - orts lst
S
while expression :
Hello, abe jones
lin ked in
statements
Conversion unctions F See also http://docs.python.org/library/
" You owe me ${0:,.2f}".format(253422.3)
stdtypes.html typess e -mutable
techieprogrammer
int(expr) Converts expr to integer # q
You owe me $253,422.30
For Loop
float(expr) Converts expr to float
for var in collection:
T echie _Programmer
str(expr) Converts expr to string
now = datetime.now()
statements Counting
chr(num) A CII char num
S
Dictionary Operations '{:%Y-%m-%d %H:%M:% }'.format(now)
S techie _programmer
For Loop
len(d) - umber of items in d
N
2012-05-16 15:04:33
for i in range(start, end [, del d[key] - emoves key from d
ked this handy cheat sheet <3
String / List / Tuple
i hope you li
R
step]) :
key in d - True if d contains
See also http://docs.python.org/library/
statements
Operations key d.keys() - eturns a list of keys in
R d
string.html formatspeci cation-mini-
# fi
language
(start is included; end is not) len(s) - length of s
See also http://docs.python.org/library/
s[i] - ith item in s (0-based)
stdtypes.html mappi ng-types-dict
#
s[start : - slice of s from start
U se ul unctions
f F
Arithmetic Operators end] (included) to end (excluded)
x in s - True if x is contained in s
exit( code ) - Terminate program with
x + yyadd
add xx--yysubtract
subtract
x not in s - True if x is not contained in s
exit code
x * yymultiply
multiply xx//yydivide
divide
s+t -the concatenation of s with t
F unction De initions f raw input( prompt ) - rint prompt and
_ " " P
x % yymodulus
modulus xx****yy xxpower
powery
s*n - n copies of s concatenated
readline() from stdi
def name(arg1, arg2, ...)
n
sorted(s ) - a sorted copy of s
statements
Assignment shortcuts:
shortcuts: xxop=
op=y
y
s.index( item) - position in s of item se input( prompt ) in ython 3
return expr
U " " P
Example: xx += 1 increments
increments xx