You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10 KiB

Python cheatsheet

(non-complete, please use, modify, (re)publish!)

In [ ]:
 

string, integer, float

In [ ]:
x = '3'
y = 3
z = 3.5
In [ ]:
type(x)
In [ ]:
type(y)
In [ ]:
type(z)
In [ ]:
print(x * y) # Works
In [ ]:
print(x + y) # Does not work: TypeError
In [ ]:
# From int to str
str(y)
In [ ]:
# From str to int
int(x)
In [ ]:
# From float to int
int(z)
In [ ]:
 
In [ ]:
 
In [ ]:
 

string operations

In [ ]:
s = 'hello!'
In [ ]:
s.upper()
In [ ]:
s.lower()
In [ ]:
s.capitalize()
In [ ]:
s.title()
In [ ]:
s.replace('e', 'a')
In [ ]:
s.strip('!')
In [ ]:
s.count('l')
In [ ]:
s.endswith('o')
In [ ]:
s.startswith('h')
In [ ]:
# format a string
name = 'you'
t = 'hello {}'.format(name)
print(t)
In [ ]:
# format a string (different way of writing the same!)
name = 'you'
t = f'hello {name}'
print(t)
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

loops

In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

lists

In [ ]:
# Make an empty list
bag = []
In [ ]:
type(bag)
In [ ]:
# Add items to the list
word = 'hello'
bag.append(word)
print(bag)
In [ ]:
# From list to string
' --- '.join(bag)
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

dictionaries

In [ ]:
# Make an empty dictionary
dict = {}
In [ ]:
dict['word'] = 10  
print(dict)
In [83]:
dict.keys()
Out[83]:
dict_keys(['word'])
In [ ]:
 
In [ ]:
 
In [ ]:
 

open(), read(), write(), close()

mode can be:

  • r when the file will only be read
  • w for only writing (an existing file with the same name will be erased)
  • a opens the file for appending, any data written to the file is automatically added to the end
  • r+ opens the file for both reading and writing

(The mode argument is optional: r will be assumed if its omitted.)

In [ ]:
# open(), read()
txt = open('txt/language.txt', 'r').read()
print(txt)
In [ ]:
# readlines()
lines = open('txt/language.txt', 'r').readlines()
print(lines)
In [ ]:
# listdir() (open multiple files in a folder)
import os
folder = 'txt/words-for-the-future/'
for file in os.listdir(folder):
    print(folder+file)
    # txt = open(folder+file).read()
    # print(txt)
In [ ]:
# write() (returns a number, this is how many characters have been written to the file)
out = open('out.txt', 'w')
out.write('Hello!')
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: