Python2 Cheat Sheet v2
Python2 Cheat Sheet v2
7
Useful String functions: Convert anything to a string:
Essentials
Make lowercase: "A".lower()="a" newstring = str(<any variable>)
POCKET REFERENCE GUIDE
Make UPPERCASE : "a".upper()="A" newstring = str(100)
SANS Institute
Make Title Format: "hi world".title()="Hi World"
Replace a substring: "123".replace('2','z')= "1z3" Convert String to Integer: www.sans.org/sec573
http://isc.sans.edu
Count occurrences of substring:"1123".count("1")=2 newint = int(<string>[,base]) Mark Baggett Twitter: @markbaggett
Get offset of substring in string: "123".index("2")=1 All of the following assign the
variable ten the integer 10
Detect substring in string: “is” in “fish” == True
>>> ten = int(“1010”,2) 3 Methods of Python Execution
Encode "a string": "a string".encode(codec name)
>>> ten = int(“0010”)
Decode a string: "a string".decode(codec name) >>> ten = int(“000A”,16) Command line Execution with -c:
Example with the ROT13 codec: # python –c [“script string”]
>>> print "RAPBQR-ZR".decode("rot13") python –c "print 'Hello World!'"
Convert Float to Integer by dropping decimal:
ENCODE-ME
newint = int(<float>)
>>> print int(3.1415) Python Interpreter Script Execution:
Some String encoders/decoder codec names: 3 # cat helloworld.py
Base64, bz2 , hex, rot13, uu, zip, string_escape >>> int(3.6) print "Hello World"
3 # python helloworld.py
Convert a string to a list (default separator=space): Hello World
newlist = astr.split(<separator>) Convert String or number to Float:
>>> print "A B C".split() afloat = float(<var>) Python Interactive Shell:
['A', 'B', 'C'] >>> print float("1.5") # python
>>> print "A B C".split() 1.5 >>> print "Hello World"
['A', 'B', 'C'] >>> print float(1) Hello World
>>> print "A,B, ,C".split(",") 1.0
['A', 'B', ' ', 'C']
>>> print "WANNA BANANA?".split("AN") Convert String Character to ASCII decimal:
['W', 'NA B', '', 'A?'] newint = ord(<string length 1>) Python Command Line Options
>>> print ord("A")
Convert a list (or other iterable object) to a string: 65 # python –c “script as string”
Join a list together putting string between elements. Execute a string containing a script
“astring”.join([list]) Convert ASCII decimal to String of length 1: # python –m <module> [module args]
>>> print "".join(['A','B','C']) newstr = chr(<integer 1 to 255>) Find module in path and execute as a script
ABC >>> print chr(65) Example: python –m “SimpleHTTPServer”
>>> print ",".join(['A','B','C']) A # python –i <python script>
A,B,C Drop to interactive shell after script execution
Loops Lists & Dictionaries Misc SEC573 PyWars Essentials