0% found this document useful (0 votes)
10 views

Python2 Cheat Sheet v2

This document provides an overview of common string, list, dictionary, and math operations in Python. It discusses how to: - Perform operations on strings like lowercase, uppercase, title case, replace, count, index, split, join - Convert between data types like string to int, float, list and vice versa - Use basic list methods like append, insert, remove, count - Create and access dictionaries - Define functions - Use conditional logic like if/else statements - Slice strings and lists - Perform mathematical operations - Loop through lists and strings

Uploaded by

h4ckm3omg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python2 Cheat Sheet v2

This document provides an overview of common string, list, dictionary, and math operations in Python. It discusses how to: - Perform operations on strings like lowercase, uppercase, title case, replace, count, index, split, join - Convert between data types like string to int, float, list and vice versa - Use basic list methods like append, insert, remove, count - Create and access dictionaries - Define functions - Use conditional logic like if/else statements - Slice strings and lists - Perform mathematical operations - Loop through lists and strings

Uploaded by

h4ckm3omg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

String Operations Converting Data Types Python 2.

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

List essentials: Adding Comments to code: Create pyWars Object


Create an empty list: newlist=[] #Comments begin the line with a pound sign >>> import pyWars
>>> game= pyWars.exercise()
Assign value at index: alist[index]= value
Access value at index alist[index] Defining Functions:
Here is a function called “add”. It accepts 2 arguments Account Mangement
Add item to list: alist.append(new item) >>> game.new_acct("username","password")
Insert into list: alist.insert(at position, new item) num1 and num2 and returns their sum. Calling “print
>>> game.login("username","password")
Count # of an item in list: alist.count( item ) add(5,5)” will print “10” to the screen: >>> game.logout()
Delete 1 matching item: alist.remove(del item)
def add(num1, num2):
Remove item at index del alist[index] Query a question:
#code blocks must be indented
#each space has meaning in python >>> game.question(<question #>)
Dictionary essentials: myresult = num1 + num2
Create an empty dict: dic={} return myresult Query the data:
Initialize a non-empty dictionary: >>> game.data(<question #>)
dic = { “key1”:”value1”,”key2”:”value2”} if then else statements:
Assign a value: dic[“key”]=”value” if <logic test 1>: Submit an answer:
Determine if key exists: dic.has_key(“key”) #code block here will execute >>> game.answer(<question #>,
#when logic test 1 is True solverfunc(game.data(<question#>)))
Access value at key: dic[“key”], dic.get(“key”)
elif <logic test 2>:
List of all keys: dic.keys() #code block executes logic test 1 is
List of all values: dic.values() #False and logic test 2 is True
List of (key,value) tuples: dic.items() else: Logic and Math Operators
#code block for else has no test and
Looping examples: #executes when if an all elif are False
Math Operator Example X=7, Y=5
For loop 0 thru 9: for x in range(10): Slicing and Indexing Strings, Lists, etc Addition X +Y 12
For loop 5 thru 10: for x in range(5,11):
Subtraction X - Y 2
For each char in a string: for char in astring:
Slicing strings and lists: Multiplication X *Y 35
For items in list : for x in alist:
x[start:stop:step] x=[4,8,9,3,0] x=”48930” Division X /Y 1
For loop retrieving indexes and values in a list : x[0] 4 ‘4’ Exponent X ** Y 16807
for index,value in enumerate(alist): x[2] 9 ‘9’
For keys in a dict : for x in adict.keys(): Modulo X%Y 2
x[:3] [4,8,9] ‘489’ Logic Operator
For all items in dict: for key,value in adict.items(): x[3:] [3,0] ‘30’
while <logic test> do: Equality X == Y False
x[:-2] [4,8,9] ‘489’ Greater Than X>Y False
x[::2] [4,9,0] ‘490’
Loop Control statements (for and while): Less Than X<Y True
x[::-1] [0,3,9,8,4] ‘03984’
Exit loop immediately break Less or Equal X <= Y True
len(x) 5 5
Skip rest of loop and do loop again continue Not Equal X !=Y or X<>Y True
sorted(x) [0,3,4,8,9] ['0', '3', '4', '8', '9']
Other Logical Operators: AND, OR and NOT

You might also like