s = "abc"
s.startswith("ab") # True, abc starts with a
s.endswith("bc") # True, abc ends with c
s.count("ab") # counts how many times "ab" appears
s.find("bc") # find the first index where "bc" appears
s.removeprefix("ab") # returns a new string with "ab" removed from the beginning
s.removeprefix("bc") # returns a new string with "bc" removed from the end
s.replace("bc", "d") # returns a new string with (every) "bc" replaced with "d"
s.strip() # returns a new string with whitespace removed from the beginning and end (rstrip and lstrip do just the end and beginning, respectively)
# returns a list of strings by splitting the original one by whitespace (note: \n is a newline, \t is a tab)
"some list\tof\nstrings".split() # ["some", "list", "of", "strings"]
# can also specify a separator
"some,list,of,strings".split(",") # ["some", "list", "of", "strings"]
# returns a string with each element of the list joined by the original string
# e.g. this would return "some, list, of, strings"
", ".join(["some", "list", "of", "strings"])
s.isalpha() # returns True if the entire string is only a-z (case-insensitive)
s.isnumeric() # returns True if the entire string is only 0-9
s.isalnum() # returns True if isalpha and isnumeric both return True
s.isascii() # returns True if the entire string is ASCII
s.isspace() # returns True if the entire string is whitespace
s.isupper() # returns True if the entire string is uppercase (also islower and istitle)
# there is also isdecimal and isdigit, see https://stackoverflow.com/a/54912545 for differences from isnumeric
# each of these returns a new string but...
s.capitalize() # Makes the first letter a capital
s.lower() # makes the string lowercase
s.upper() # MAKES THE STRING UPPERCASE
s.title() # Makes Each Word Capitalised
s.center(30) # centers the string (with spaces by default, but this can be customised) using the given width
# e.g.
print(" Some Section Title ".center(40, "=")) # ========== Some Section Title ==========
nums = [1, 2, 3]
nums[1] # 2 (item at index 1)
nums[-1] # 3 (first item from the end)
nums[-2] # 2 (second item from the end)
nums.index(3) # returns index where 3 is first found (2 in this case)
nums.count(1) # returns number of times 1 is present in the list
nums.append(1) # adds 1 to the end of the list
nums.insert(0, 10) # inserts 10 at 0th index
nums.extend(someOtherList) # attaches someOtherList to nums
nums.remove(3) # removes all instances of 3
nums.pop() # removes last element and returns it (i.e. you can do a = nums.pop())
nums.pop(1) # removes element at index 1 and returns it
nums.reverse() # reverses original list (this will *modify* the list)
nums.sort() # sorts list (this will *modify* the list, and will also *not* return the sorted array)
things = {"a": 1, "b": 2, "c": 3}
things["a"] # 1
things.get("a") # 1
things["d"] # raises (throws) KeyError
things.get("d") # None
things.keys() # ["a", "b", "c"]
things.values() # [1, 2, 3]
things.items() # [('a', 1), ('b', 2), ('c', 3)]
# can be used to loop like so:
for k, v in things.items():
print(k, v) # a 1, b 2, c 3
things.copy() # returns copy of the dictionary
things.pop("a") # removes "a" from dictionary
things.popitem() # removes most recent pair added
# sets are lists but items must be unique and order is ignored
nums = {1, 2, 3}
nums.add(item) # adds item to set if its not there already
nums.remove(item) # remove item, throws error if not present
nums.discard(item) # removes item, does not throw error
nums.isdisjoint(anotherSet) # returns true if no common elements
nums.issubset(anotherSet) # returns true if all elements from anotherSet is present in original set
nums.issuperset(anotherSet) # returns true if all elements from original set is present in anotherSet
nums.difference(anotherSet) # returns set containing items ONLY in first set
nums.intersection(anotherSet) # returns new set with common elements (the middle of a venn diagram)
nums.symmetric_difference(anotherSet) # returns set containing all non-common elements of both sets (the circles of a venn diagram, but not the middle)
nums.union(anotherSet) # returns set containing all elements of both sets (both circles of venn diagram)
# the above 4 operations can also be done this like:
nums - anotherSet
nums & anotherSet
nums ^ anotherSet
nums | anotherSet
# example:
a = {1,2,3}
b = {3,4,5}
print(a - b) # {1, 2}
print(a & b) # {3}
print(a ^ b) # {1, 2, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
s = """
hi this is a string
with multiple lines
wow
isnt this cool
"""
a = 123
b = [1, 2, 3]
# pretty much any python value/object can be put in a format string
print(f"the digits of {a} are {b}") # the digits of 123 are [1, 2, 3]
# you can set the decimal precision using .2f
price = 1.2
print(f"Total Price: ${price:.2f}") # Total Price: $1.20
# you can put more complex expressions, not just variables (including other format strings!)
# but note that except on python 3.12, you can't nest the same type of quotes
# i.e. if you use double quotes for the format string, any strings in your expressions must use single quotes
print(f"its just {' '.join(['that', 'easy'])}") # its just that easy
# how deep can we go?
print(f"""level 1 {f"level 2 {'level 3'}"}""")
nums = [9, 2, 4, 7, 7, 3, 0, 2, 3, 1] # or some other iterable, like a string
# i = ^0 ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9
# iterable[i:j:k] => gets every kth item, from index i (inclusive) to index j (exclusive)
print(nums[1:6:2]) # prints [2, 7, 3]
print(nums[1:5:2]) # prints [2, 7]
# you can omit parts you dont need
print(nums[3:]) # prints index 3 onwards: [7, 7, 3, 0, 2, 3, 1]]
print(nums[:4]) # prints first 4 items (i.e. up to index j - 1): [9, 2, 4, 7]
print(nums[::2]) # prints every 2nd item: [9, 4, 7, 0, 3]
print(nums[:]) # prints a copy of the list: [9, 2, 4, 7, 7, 3, 0, 2, 3, 1]
# negative numbers are allowed
print(nums[-3:]) # prints last 3 items: [2, 3, 1]
print(nums[:-4]) # prints every item except the last 4: [9, 2, 4, 7, 7, 3]
print(nums[::-1]) # prints the list reversed: [1, 3, 2, 0, 3, 7, 7, 4, 2, 9]
The star operator (*
) allows you to "spread out" a list or tuple as function arguments:
from math import pow
# pow(a, b) = a to the power of b, pow(2, 2) = 4, pow(3, 4) = 81
args = (2, 5)
print(pow(*args)) # 32
args = (4, 4)
print(pow(*args)) # 256
Some useful modules that I cbf writing about:
- Regular Expressions: https://docs.python.org/3/library/re.html
- Very useful for manipulating strings, e.g. finding something in a string.
- itertools: https://docs.python.org/3/library/itertools.html
- Very useful iterator functions, kind of hard to explain.
- Math: https://docs.python.org/3/library/math.html
- Random Numbers: https://docs.python.org/3/library/random.html
- Includes useful functions like "shuffle" and "choice" for lists.
- Exact Decimal Math: https://docs.python.org/3/library/decimal.html
- Time: https://docs.python.org/3/library/time.html
- e.g. getting a timestamp, sleeping for 2 seconds, etc.
- For actual date/time logic, use https://docs.python.org/3/library/datetime.html
Full listing of the standard library: https://docs.python.org/3/library/index.html
import antigravity
Sometimes you need all the lowercase letters (or similar). You could just type out abcdef... but fuck that.
import string # singular, not plural, i always forget
print(string.ascii_lowercase) # abcdef...
print(string.ascii_uppercase) # ABCDEF...
print(string.ascii_letters) # both of the above
print(string.digits) # 0123456789
print(string.hexdigits) # 0123456789abcdefABCDEF
print(string.octdigits) # 01234567
print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.whitespace) # whitespace characters (e.g. tab, space, newline, and weirder ones)
print(string.printable) # all of the above
Docs: https://docs.python.org/3/library/string.html
Loops over two lists/iterables together. Ends with the first one.
for a, b in zip("abcdef", [1,2,3]):
print(a, b)
Prints:
a 1
b 2
c 3
Whenever you access a key that doesn't exist, it calls a function to give you a default value:
from collections import defaultdict
def make_default():
return "abc"
things = defaultdict(make_default)
things["a"] = "def"
print(things["a"], things["b"]) # def abc
Other useful collections (like Counter): https://docs.python.org/3/library/collections.html