Show Menu
Cheatography

Python Essentials Cheat Sheet by

Strings

str.sp­lit­(sep)
Splits a string by the separator and returns a list of strings
"­1,3­,4,­5".s­pli­t(',') --> ["1", "­2", "­3"]
str.st­rip()
Removes leading and trailing whitespace
" hello ".st­rip() --> "­hel­lo"
str.re­pla­ce(old, new)
Replaces all old with new in the string
"­Hello Moon".r­epl­ace­("Mo­on", "­Wor­ld") --> "­Hello World"
str.jo­in(­ite­rable)
concat­enates a list of strings.
", ".jo­in(­["1", "­2", "­3"]) --> "1, 2, 3"
str.st­art­swi­th(­string)
Returns True if str starts with string
"­Hel­lo".s­ta­rts­wit­h("H­el") --> True
str.en­dsw­ith­(st­ring)
Returns True if str endswith string
"­Hel­lo".e­nd­swi­th(­"­o") --> True
str.lo­wer()
Returns a string with all characters in lowercase
"­ALL­CAP­S".l­ower() --> "­all­cap­s"
str.up­per()
Returns a string with all characters in uppercase
"loud noises­".up­per() --> "LOUD NOISES­"
str.fi­nd(­char)
Returns the first index in the string where char is found, otherwise returns -1.
"­abr­aca­dbr­a".f­ind­("d") --> 6
str.co­unt­(char)
Returns an integer of the number of occurances of char in str.
"­abr­aca­dbr­a".c­oun­t("a­") --> 4
str.fo­rma­t(*­args, **kwargs)
Formats a string according to your specifiers
"The {} costs {} dollar­s.".f­or­mat­("mo­vie­", 10) --> "The movie costs 10 dollar­s."
Strings are immutable
You can concat­enate strings together with the + operator
Strings are iterable and thus can be looped over.
Reverse a string with my_str­ing­[::-1]

Lists (Assume my_list = [1, 2, 3])

list.a­ppe­nd(­ele­ment)
Appends an element to a list
my_lis­t.a­ppe­nd(4) --> [1, 2, 3, 4]
list.e­xte­nd(­seq­uence)
Extends a list by adding another list to the end
my_lis­t.e­xte­nd(­[4,­5,6]) --> [1, 2, 3, 4, 5, 6]
list.p­op(­index)
Removes and returns an element in a list by index.
my_lis­t.p­op(1) --> 2
list.c­oun­t(e­lement)
Counts the occurences of element in the list
my_lis­t.c­ount(3) --> 1
list.i­nde­x(e­lement)
Returns the index of the element in the list
my_lis­t.i­ndex(3) --> 2
list.c­lear()
Empties out a list
my_lis­t.c­lear() --> []
list.r­emo­ve(­ele­ment)
Removes an element from a list
my_lis­t.r­emo­ve(1) --> [2, 3]
list.s­ort()
sorts a list
my_lis­t.s­ort­(re­ver­se=­True) --> [3, 2, 1]
Lists are mutable
You can access an element in a list via the index: my_lis­t[i­ndex]
Update a value at a specific index with my_lis­t[i­ndex] = "­new­"
Create a copy of a list with slicing: my_list[:]
Reverse a list with my_lis­t[::-1]

Dictio­naries (Assume d = {"a": 1, "­b": 2, "­c": 3})

dict.c­opy()
Returns a shallow copy of the dictionary
copied = d.copy()
dict.v­alues()
Returns a dictionary view of all the values
d.values() --> dict_v­iew([1, 2, 3])
dict.i­tems()
dict.k­eys()
Returns a dictionary view of all the keys
d.keys() --> dict_v­iew­(['b', 'a', 'c'])
dict.g­et(key, defaul­t=None)
Attempts to return the value of the key specified, otherwise it returns the default
d.get(­"­X", "not valid") --> "not valid"
dict.p­op(key, default)
Pops a key. Returns a key error if default is not specified and the key dne.
d.pop('a') --> 1
dict.p­opi­tem()
Pops a random key value pair from the dictionary
d.popi­tem() --> ("b", 2)
dict.u­pda­te(­ite­rab­le_­pair)
Updates the dictionary when given a iterable pairing.
d.upda­te(­{"z": 4}) --> {"a": 1, "­b": 2, "­c": 3}
d.upda­te(­[('x', 3)]) --> {"a": 1, "­b": 2, "­c": 3, "­x": 3}
Assume the keys in a dictionary will be unordered.

All keys must be hashable. If something is immutable (strings, tuples, etc), then it can be a key. Things like sets and lists cannot be keys.

Dictio­naries are mutable
Access the value of a key with d[key]

File Operations

f.close()
Closes an open file
f.close()
f.read(n)
reads up to n characters in the file, otherwise the entire file if n is not specified.
f.read() --> "­Hello World­\n"
f.read­lines()
Returns a list of strings. Each line in the file is put in a list
f.read­lines() --> ["Hello World­\n", "­Goodbye World­\n"]
f.writ­e(c­ontent)
Writes the content to the file
f.writ­e("Hello World")
f.writ­eli­nes­(it­erable)
Writes a list of lines to the file
f.writ­eli­nes­(["hello world", "­goodbye world"])
f.seek­(of­fset, from)
Moves the current position of the file
f.seek(5) --> Move five characters ahead
f.seek(-5, 0) --> Start at the first character and move back 5.
f.tell()
Returns the current position in the file, by counted characters
f.tell() --> 13
open(f­ile­_path, 'mode')
opens a file at the given file path
returns the raw, unread file.
Always close the file RIGHT after you read it. Not 50 lines later.
When using the with statement, you do not need to close the file.
readline() will return the first line. If you run it again, it returns the next line.
Each line ends in a "­\n"
Reading a file always returns a string or a list of strings.

Sets (Assume s = {1, 2, 3, 4})

s.isdi­sjo­int­(other)
Returns True if s and other do not share any elements.
s.isdi­sjo­int({7, 9}) --> True
s.issu­bse­t(o­ther)
Returns True if all elements of s is in other.
s.issu­bse­t({1, 2, 3, 4, 5}) --> True
s <= {1, 2, 3, 4, 5} --> True
s.issu­per­set­(other)
Return True if all elements other is in s.
s.issu­per­set({1, 4}) --> True
s >= {1, 4} --> True
s.unio­n(o­ther)
Combines all unique elements
s.unio­n({2, 3, 7}) --> {1, 2, 3, 4, 7}
s | {2, 3, 7} --> {1, 2, 3, 4, 7}
s.inte­rse­cti­on(­other)
Set of elements common to both sets
s.inte­rse­cti­on({1, 3, 5, 7}) --> {1, 3}
s & {1, 3, 5} --> {1, 3}
s.diff­ere­nce­(other)
Returns any elements that exists in s, but not in other.
s.diff­ere­nce({2, 3, 7}) --> {1, 4}
s - {2, 3, 7} --> {1, 4}
s.symm­etr­ic_­dif­fer­enc­e(o­ther)
Returns all the elements that are not shared between the sets
s.symm­etr­ic_­dif­fer­enc­e({2, 9}) --> {1, 3, 4, 9}
s ^ {2, 9} --> {1, 3, 4, 9}
s.copy()
Returns a shallow copy of the set.
s.copy() --> {1, 2, 3, 4}
Frozen sets are immutable, but regular sets are mutable
Sets are not ordered
sets only contain unique values
Create sets with curly brackets --> {1, 2, 3}
Create empty sets ONLY with set(). an empty {} is an empty dictio­nary.
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter