Blogpost

Published: 2020-06-30

Python3 cheatsheet

I rarely use python, when I do, I always forget about the basics. Here you can find a list of the stuff I need to remind myself time and time again.

Terminal

Table of contents

Loops

Lists

for animal in ["dog", "cat", "mouse"]:

Dictionary

for key, value in {"one": 1, "two": 2, "three": 3}.items():

Lists/Arrays

l = [1, 2, 3]
length = len(l)
first_element = l[0]

Algebraic structures

  • map x = map(a_function, iterable)

Sorting

  • Manipulates the list l.sort(key=lambda k: k[0], reverse=True).
  • Returns a new list, the original list remains untouched sorted(l, key=lambda k: k[0], reverse=True)

Functions

def named_function(x = 1, y = 2):
    return x, y # returns a tuple

x, y = named_function()

Strings

  • substring my_string[0:5]
  • contains substring - 'substring' in my_string
  • parse string(a_number)
  • interpolation f'Hello {who}!' where who is a variable
  • join '-'.join(list)

Regular expression

import re
match = re.search(r"\w+/[\d]+/([\d]+)", searchString)
full_match = match.group(0)
group1 = match.group(1)

Types

Parse

  • float(someString)
  • int(someString)

Type Check

  • isinstance(test_string, str)

Random

import random
random.random()

Sleep

import time
time.sleep(2.4)

Sources

Tags

#python #cheatsheet