28 Python Cheat Sheet
28.1 Data Structure Initialization
28.2 Basic Operations and Data Types
| Function/Method | Example Application | Explanation |
|---|---|---|
print() |
print("String")my_name = "Bram"print(my_name) |
Displays the value inside its parentheses on the screen. |
len() |
my_name = "Bram"length_name = len(my_name)print(length_name) |
Counts the number of characters in a string. |
input() |
my_name = input()my_name = input("name:") |
Reads a string from standard input. |
str() |
grade = 9.8string_grade = str(grade) |
Converts a specific variable into a string. |
int() |
grade = 9.8int_grade = int(grade) |
Converts a specific variable into an integer. |
float() |
grade = 9float_grade = float(grade) |
Converts a specific variable into a float. |
range() |
for i in range(1,10):print(i) |
Generates a sequence of numbers within a specified range. |
28.3 String Manipulation
| Function/Method | Example Application | Explanation |
|---|---|---|
upper() |
spam = "laptop"spam = spam.upper() |
Converts all letters in the string to uppercase. |
lower() |
spam = "LAPtop"spam = spam.lower() |
Converts all letters in the string to lowercase. |
islower() |
spam = "LAPtop"check = spam.islower() |
Returns True when all letters are lowercase, otherwise False. |
isupper() |
spam = "LAPTOP"check = spam.isupper() |
Returns True when all letters are uppercase, otherwise False. |
isalpha() |
spam = "laptopfromJohnny"check = spam.isalpha()print(check) |
Returns True if the string consists only of letters and isn’t blank. |
isalnum() |
spam = "laptopfromBOB789"check = spam.isalnum()print(check) |
Returns True if the string consists only of letters and numbers and is not blank. |
isdecimal() |
spam = "888888"check = spam.isdecimal()print(check) |
Returns True if the string consists only of numeric characters and is not blank. |
isspace() |
spam = " \n"check = spam.isspace()print(check) |
Returns True if the string consists only of spaces, tabs, and newlines and is not blank. |
istitle() |
spam = "De Title Van Het Boek"check = spam.istitle()print(check) |
Returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters. |
startswith() |
spam = "De Title Van Het Boek"check = spam.startswith("De")print(check) |
Returns True if the string value called on, begins with the string passed to the method. |
endswith() |
spam = "De Title Van Het Boek"check = spam.endswith("ek")print(check) |
Returns True if the string value they are called on ends with the string passed to the method. |
join() |
my_list = ["My", "name", "is", "Alberto"]sentence = ' '.join(my_list)print(sentence) |
Joins strings together with a specified separator. |
split() |
my_sentence = "My name is Alberto"the_list = my_sentence.split()print(the_list) |
Splits a string into a list of substrings based on a separator. |
partition() |
my_sentence = "My name is Alberto"the_list = my_sentence.partition("is")print(the_list) |
Splits a string into three parts based on a separator. |
rjust() |
my_name = 'Alberto'print_name = my_name.rjust(40)print(print_name) |
Right-aligns a string within a specified width. |
ljust() |
my_name = 'Alberto'print_name = my_name.ljust(40)print(print_name) |
Left-aligns a string within a specified width. |
center() |
my_name = 'Alberto'print_name = my_name.center(40)print(print_name) |
Centers a string within a specified width. |
28.4 Random
| Function/Method | Example Application | Explanation |
|---|---|---|
random.randint() |
(import random)r = random.randint(1, 100)print(r) |
Generates a random integer within a specified range. |
random.choice() |
(import random)my_list = ['Boom', 'Huis', 'Auto']choice = random.choice(my_list)print(choice) |
Selects a random element from a list. |
random.shuffle() |
(import random)my_list = ['Boom', 'Huis', 'Auto']random.shuffle(my_list)print(my_list) |
Shuffles the elements in a list randomly. |
random.sample() |
(import random)my_list = ['Boom', 'Huis', 'Auto']shuffled_list = random.sample(my_list, len(my_list))print(my_list)print(shuffled_list) |
Generates a random sample from a list without replacement. |
28.5 Lists
| Function/Method | Example Application | Explanation |
|---|---|---|
index() |
my_list = ['Boom', 'Huis', 'Auto']x = my_list.index('Huis') |
Returns the index of the first occurrence of an item in a list. |
enumerate() |
my_list = ['Boom', 'Huis', 'Auto']for i, value in enumerate(my_list):print(f"{i}: {value}") |
Adds a counter to an iterable and returns it as an enumerate object. |
append() |
my_list = ['Boom', 'Huis']my_list.append('Auto')print(my_list) |
Adds an item to the end of a list. |
list() |
letter_list = list(dict.keys()) |
Converts a dictionary’s keys into a list. |
insert() |
my_list = ['Boom', 'Huis']my_list.insert(1, 'Auto')print(my_list) |
Inserts an item at a specified position in a list. |
remove() |
my_list = ['Boom', 'Huis', 'Auto']my_list.remove('Huis')print(my_list) |
Removes the first occurrence of an item from a list. |
sort() |
my_list = ['Boom', 'Huis', 'Auto']my_list.sort()print(my_list) |
Sorts a list in ascending order. |
reverse() |
my_list = ['Boom', 'Huis', 'Auto']my_list.reverse()print(my_list) |
Reverses the elements of a list in place. |
28.6 Dictionaries
| Function/Method | Example Application | Explanation |
|---|---|---|
update() |
my_dict = {'color1': 'Red', 'color2': 'Green'}my_dict.update({'color3': 'Blue'})print(my_dict) |
Updates a dictionary with elements from another dictionary. |
values() |
my_dict = {'color1': 'Red', 'color2': 'Green', 'color3': 'Blue'}for v in my_dict.values():print(v) |
Returns a view of the values in a dictionary. |
items() |
my_dict = {'color1': 'Red', 'color2': 'Green', 'color3': 'Blue'}for i in my_dict.items():print(i) |
Returns a view of the key-value pairs in a dictionary. |
keys() |
my_dict = {'color1': 'Red', 'color2': 'Green', 'color3': 'Blue'}for k in my_dict.keys():print(k) |
Returns a view of the keys in a dictionary. |
get() |
my_dict = {'color1': 'Red', 'color2': 'Green', 'color3': 'Blue'}color4 = my_dict.get('color4', 'D.N.E.')print(color4) |
Returns the value for a specified key if key is |
28.7 Files
| Function/Method | Example Application | Explanation |
|---|---|---|
Path() |
from pathlib import PathfilePath = Path('Boom', 'Huis', 'Auto')print(filePath) |
Creates a file path object. |
path.home() |
from pathlib import Pathprint(Path.home()) |
Retrieves the home directory path. |
os.makedirs() |
import osos.makedirs('C:\Basisbeginselen programmeren\Test') |
Creates a new directory path. |
mkdir() |
from pathlib import PathPath(r'C:\Basisbeginselen programmeren\Test2').mkdir() |
Makes a directory from a Path object. |
path.cwd() |
from pathlib import Pathprint(Path.cwd()) |
Retrieves the current working directory path. |
open() |
openFile = open(Path(r'C:\DAP') / 'textfile.txt') |
Opens a file for reading or writing. |
read() |
openFile = open(Path(r'C:\DAP') / 'textfile.txt')content = openFile.read()print(content) |
Reads the entire content of a file. |
readlines() |
openFile = open(Path(r'C:\DAP') / 'textfile.txt')content = openFile.readlines()print(content) |
Reads the file content line by line. |
close() |
openFile.close() |
Closes an opened file. |
write() |
openFile = open(Path(r'C:\DAP') / 'textfile.txt', 'w')openFile.write('Hoi')openFile.close() |
Writes content to a file. |
shutil.copy() |
import shutilfile = Path(r'C:\DAP') / 'TextFile.txt'copy = Path(r'C:\DAP') / 'COPY_TextFile.txt'shutil.copy(file, copy) |
Copies a file to a new location. |
shutil.copytree() |
import shutilfolder = Path(r'C:\DAP')folder2 = Path(r'C:\DAP_COPY')shutil.copytree(folder, folder2) |
Copies an entire directory to a new location. |
shutil.move() |
import shutilfolder = Path(r'C:\DAP2\DAP_COPY') / 'TextFile.txt'folder2 = Path(r'C:\Basisbeginselen programmeren')shutil.move(folder, folder2) |
Moves a file or directory to a new location. |