# Lowercasestr.lower() # hello world# Uppercasestr.upper() # HELLO WORLD# Capitalize (first letter of string upper, rest lower)str.capitalize() # Hello world# Title case (first letter of each word upper, rest lower)str.title() # Hello World# Swap case (reverses case of each letter)str.swap() # hELLO wORLD
Search
#does string contain substring?str.find("foo", [beg=0, end=len(str)])
# same as find, but raises an exception if substring not foundstr.index("foo", [beg=0, end=len(str)])
# if string starts with substringstr.startswith("foo", [beg=0, end=len(str)])
# if string ends with substringstr.endswith("foo", [beg=0, end=len(str)])
# count how many times substring occours in stringstr.count("foo", [beg=0, end=len(str)])
Character classifiers
# Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.str.isalnum()
# Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.str.isalpha()
# Returns true if string contains only digits and false otherwise.str.isdigit()
# Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.str.islower()
# Returns true if a unicode string contains only numeric characters and false otherwise.str.isnumeric()
# Returns true if string contains only whitespace characters and false otherwise.str.isspace()
# Returns true if string is properly "titlecased" and false otherwise.str.istitle()
# Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.str.isupper()
# Returns true if a unicode string contains only decimal characters and false otherwise.str.isdecimal()
Formatting
# Basic formattingprice=49txt="The price is {} dollars"print(txt.format(price))
# Format the price to be displayed as a number with two decimals:txt="The price is {:.2f} dollars".format(price)
# indexed formattingquantity=3itemno=567price=49myorder="I want {0} pieces of item number {1} for {2:.2f} dollars."print(myorder.format(quantity, itemno, price))
#named indiciesmyorder="I have a {carname}, it is a {model}."print(myorder.format(carname="Ford", model="Mustang"))
Character and ASCII
# Get ASCII code of characterord('A') #65# Get character from ASCII codechr(97) #'a'
Character groups
# useful library for getting groups of strings/charactersimportstring# all uppercase lettersstring.ascii_uppercase# ABCDEFGHIJKLMNOPQRSTUVWXYZ# same for lowercasestring.ascii_lowercase# abcdefghijklmnopqrstuvwxyz# or get both in onestring.ascii_letters# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ# digits as wellstring.digits# 0123456789
Lists and Dictionaries
Comprehension
# List comprehension
[xforxinlist]
# Nested list comprehension
[xforxinyifx%2==0foryinitemsiflen(y) >2]
# Dictionary comprehension (list of tuples to dictionary)
{key:valuefor (key, value) initems}
# Dictionary to list of tuples
[(key, value) forkey, valueinitems]
Sortering
in-place sorting
# Sorting in-placeitems.sort()
# Sort using custom key (can either be lamda or a method ref)items.sort(key=lambdael: el[0])
# Sort in reverse orderitems.sort(reverse=True)
sort into new list
# Sorting into copy of listsortedItems=sorted(items)
# Sort using custom key (can either be lamda or a method ref)sortedItems=sorted(items, key=lambdael: el[0])
# Sort in reverse ordersortedItems=sorted(items, reverse=True)
Modification
Reverse
# in-placeitems.reverse()
# creates a copy reversedItems=reversed(items)
Slicing
# General notationa[start:stop:step] # start through not past stop, by step# Simple examplesa[start:stop] # items start through stop-1a[start:] # items start through the rest of the arraya[:stop] # items from the beginning through stop-1a[:] # a copy of the whole array# Negative examplesa[-1] # last item in the arraya[-2:] # last two items in the arraya[:-2] # everything except the last two items#Step examplesa[::-1] # all items in the array, reverseda[1::-1] # the first two items, reverseda[:-3:-1] # the last two items, reverseda[-3::-1] # everything except the last two items, reversed
Iterables
Enumerate
# Enumerate over an iterable with a corresponding indexenumerate(iterable, [start=0])
# Basic examplewords= ["foo", "bar", "baz"]
fori, wordinenumerate(words):
print(i, word) # prints (0, foo)# (1, bar)# (2, baz)# Alternativly an offset can be givenfori, wordinenumerate(words, 42):
print(i, word) # prints (42, foo)# (43, bar)# (44, baz)
Zip
# Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.zip(*iterables)
# Iterate over two corresponding listsstudents= ["Jacob", "Poppy", "Jonas"]
coolnesses= [10, 10, 10**8]
forstudent, coolnessinzip(students, coolnesses):
print(student, coolness)
# prints Jacob 10# Poppy 10# Jonas 100000000# Iterate over three corresponding listsacronyms= [
"Analysis, Design and Software Architecture",
"Mobile and Distributed Systems",
"Introduction to Database Design"
]
subjects= ["BDSA", "MODIS", "IDD"]
ectses= [15,7.5,7.5]
foracronym, subject, ectsinzip(acronyms, subjects, ectses):
print(acronym, subject, ects)
# prints Analysis, Design... 15 BDSA# Mobile and Distr... 7.5 MODIS# Introduction to ... 7.5 IDD
Templates
Input readers
# read n lines using for loopcases=int(input())
foriinrange(cases):
#code#read n lines using list comprehensionn=int(input())
cases= [input() forxinrange(n)]
# while not 0 0line=input()
whileline!="0 0":
#codeline=input()
#until end of fileimportsysforlineinsys.stdin:
line=line.strip() #remove those pesky newline characters#code#assign numbers on line to intsa, b, c=map(int, input().split(" "))
Algorithms
BFS - Breadth first search (with lazy construction of graph)
#bfsdefgenerateOptions(origin):
result= []
#add options to resultreturnresultstart=""#starting valuegoal="goal"#goal valuefromMap= {start:start}
used=set()
whilegoalnotinfromMap:
currentList= [xforxinfromMapifxnotinused]
foritemincurrentList:
forsubItemingenerateOptions(item):
ifsubItemnotinfromMap:
fromMap[subItem] =itemused.add(item)
path= [goal]
current=goalwhilecurrent!=start:
current=fromMap[current]
path.append(current)
path.reverse()
# path is now a the sortest list of verticies from start to goal
defrotate_matrix( m ):
return [[m[j][i] forjinrange(len(m))] foriinrange(len(m[0])-1,-1,-1)]
Useful Libraries
time
# does all things timeimporttime# get the current time in milisecondstime.time()
itertools
# does interesting stuff with iterationsimportitertools# count counts (duh)itertools.count(10) # 10 11 12 13 14 ...# you can also specify stepitertools.count(2.5, 0.5) # 2.5 3.0 3.5 ...# you can cycle a list indefinitelyitertools.cycle('ABCD') # A B C D A B C D A B C D ...# permutations are also a thingitertools.permutations(range(3)) # 012 021 102 120 201 210# you can also ask it to pick to limit permutaitonsitertools.permutations('ABCD', 2) # AB AC AD BA BC BD CA CB CD DA DB DC# same thing for combinationsitertools.combinations('ABCD', 2) # AB AC AD BC BD CD