0% found this document useful (0 votes)
8 views

Corisco Strings Lists Tuples and Dictionaries in Python - BW

Uploaded by

dakec42763
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Corisco Strings Lists Tuples and Dictionaries in Python - BW

Uploaded by

dakec42763
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

strings, lists, tuples and dictionaries in python Cheat Sheet

by corisco via cheatography.com/167022/cs/34954/

STRINGS Modify strings (cont)

Strings string = "​wor​ds" or 'words' maxsplit is optional, all occurr​ences is defaul​t(-1) string.sp​lit​("-
conect string​1+s​tring2 ",1)

multiply string*3 find string string.fi​nd(​"​val​‐


ue",​sta​rt,end)
compare ('if' or 'if string1 == string2 (or != or > or <)
not') find the first occurrence of a substring in a string string.fi​nd(​"​‐
sub​str​ing​")
check ('if or 'if not') 'subst​ring' in string
start and end are optional string.fi​nd(​"​‐
position string[0] or string[-1] or string[x]
sub​str​‐
slicing string​[st​art​:en​d:step]
ing​"​,3,10)
string[:3] or string[1:]
returns the position of the substring
string​[::-1] inverted
index and find are the same, except that when string.in​dex​‐
false find returns -1 and index returns error ("su​bst​rin​g")
Slicing strings
lowercase string.lo​wer()
slicing: string​[st​art​:en​d:step]
uppercase string.up​per()
from start to end string​[2:5]
capitalize first char upper string.ca​pit​‐
from start string[:5] alize()
to the end string[2:] title first char of each word upper string.ti​tle()
jumping string​[2:5:2] join values of a list/d​ict​/tuple/ into string ' '.join​(list)
negati​ve/​inv​erted string​[::-1] count the occurences of substring in a string string.co​unt​('s​‐
ubs​tring')
Modify strings

remove whites​paces before and string.st​rip() Format strings


after the string str.format 'Hello, {} and {}'.fo​rma​t(s​tring, string2)
or remove any 'chara​cters' string.st​rip​('ch') f-string (3.6+) f'Hello, {string} and {string2}'
only before​(left) the string string.ls​trip() Integer numbers into f'Hello, {strin​g:_}'
only after(​right) the string string.rs​trip() strings*
replace string string.re​pla​ce(​"old value", "new 'b' - binary {string:b}
value", counter) 'c' - character (ASCII) 'Hello, {examp​le:​c}'.fo​rma​t(e​xample =
counter is how many occurences from start, nothing is default and 'String', ...)
means every occurrence 'd' - decimal 'Hello, {0:d} and {1}.fo​rma​t(s​tri​ng,​str​‐
use it to remove whites​paces string.re​pla​ce(​" ", "​") ing2)
inside the string 'o' - octal {string:o}
split strings create list from string.sp​lit​(se​par​ato​r,m​axs​plit) 'x' - hexade​cimal, 'Hello, {0.x} and {0:X}.f​or​mat​(st​ring)
strings lowercase
separator is optional, string.sp​lit​(",")
whitespace is default

By corisco Published 7th November, 2022. Sponsored by Readable.com


cheatography.com/corisco/ Last updated 5th November, 2022. Measure your website readability!
Page 1 of 3. https://readable.com
strings, lists, tuples and dictionaries in python Cheat Sheet
by corisco via cheatography.com/167022/cs/34954/

Format strings (cont) LISTS

'X' - hexade​cimal, {string:X} Lists list = ["st​rin​g", "​str​ing​2", integer, Bool]


uppercase ordered, change​able, list = [item1, item2, item3]
'n' - number, decimal in {string:n} allow duplicates
local language OS Lenght len(list)
Floati​ng-​point f'{int​ege​r:f}' (6 standard) Access [start index list[1] / list[-1], list[2:5], list[:5]
round(a,2) f'{int​ege​r:.2f}' (2 decimal digits) includ​ed:end index not]
'e' ou 'E' - scientific {:e}.f​orm​at(999) Check if Item exists if "​ite​m" in list:
notation (6 standard) Change items list[3] = "​new​_va​lue​"
'E' - scientific notation (6 f'{999​:.3E}' range of items list[2:5] = "​new​_va​lue​1", "​new​_va​lue​2"
standard)
insert​(in​dex​,value) list.i​nse​rt(2, "​ite​m")
'g' precisão >=1, round {:g}.f​orm​at(​12.1​23​123​5843) without replacing any
digits p to signif​icant digit item
'n' - same as 'g', but local f'{12.1​23​123​584​3:n}' append() add item to the list.a​ppe​nd(​"​ite​m")
language OS end
'%' - multiply the number f'{0.0​5:%}' extend() add items from list.e​xte​nd(​list2)
*100 and '%' after other list
two digits before '.' and '{:2.2​%}'.fo​rma​t(0.05) works with tuples also list.e​xte​nd(​tuple)
two after
remove() remove first list.r​emo​ve(​"​str​ing​")
Spacing matching value
'<' left align / '^' center '{0:<1​6}'.fo​rma​t(s​tring) / f.'{st​rin​g:^16}' / pop() remove specified list.p​op(1)
align / '>' right align {:>16} index, and returns it
number of digits {:4) del() remove specified list.d​el(3)
whites​paces if the string {strin​g:16} index
has less than 16.. clear() empties the list list.c​lear()
choose char instead of {*:16} sort() sort the list alphan​‐ list.s​ort()
whitespace ume​rically
sort descending list.s​ort​(re​ver​se=​True)
COLLEC​TIONS
reverse() order list.r​eve​rse()
List collection which is ordered and change​able. Allows
copy() make a copy list2 = list.c​opy()
duplicate members.
or use list() list3 = list(l​ist2)
Tuple collection which is ordered and unchan​geable. Allows
duplicate members. Concat​enate Lists list3 = list1 + list2

Dictionary collection which is ordered and change​able. No or use extend() list.e​xte​nd(​list2)


duplicate members. count() returns the list.c​ount() / list.c​oun​t('​value')
Set collection which is unordered, unchan​geable, and number of items*
unindexed. No duplicate members. index() finds the item and list.i​nde​x('​value')
return its index
min() / max() / sum() list.min() list.max() list.sum()

By corisco Published 7th November, 2022. Sponsored by Readable.com


cheatography.com/corisco/ Last updated 5th November, 2022. Measure your website readability!
Page 2 of 3. https://readable.com
strings, lists, tuples and dictionaries in python Cheat Sheet
by corisco via cheatography.com/167022/cs/34954/

LISTS (cont) DICTIO​NARIES

enumer​ate​(index, value) for i, v in enumer​ate​(list): /n "{i} : {v}' Dictio​naries dict = {"ke​y":"v​alu​e", "​key​2":"v​alu​e2"}
for loop for x in list: ordered, change​​able, do dict={​"​key​1": bool,"k​ey2​"​:int, "​key​3":
through index for x in range(​len​(li​st)): not allow duplicates [list]}

while loop while x <= len(list): /n i+=1 dict cannot have same keys

list compre​ehe​nsion [print[x] for x in list] Lenght len(dict)


Access get the value of value1 = dict["k​ey1​"]
TUPLES the "​key​"

Tuples tuple = ("va​lue​1", int, bool ,"va​lue​1") dict.g​et(​"​key​"​,"return if value4 = dict.g​et(​"​key​4", "Not found")
not found")
are unordered, unchan​‐ tuple = (item1,)
geable, allow duplicates List of Keys x = dict.k​eys()

Lenght len(tuple) Check if key exists if "​​ke​ys" in dict:

Access [start index tuple[1] / tuple[-1], tuple[​2:5], tuple[:5] if values exists if "​val​ue1​" in dict.v​alues()
includ​​ed:end index not] Change values of a key dict["k​ey"] = value
Check if Item exists if "​​it​e​m​" in tuple: using update() dict.u​pda​te(​{'k​ey'​:'v​alue'})
Change items tuples are list = list(t​uple) Add dict["k​ey"] = value
unchan​geable
also can use update() dict.u​pda​te(​{'k​ey'​:'v​alue'})
convert tuple to list and tuple = tuple(​list)
Remove .pop or popite​‐ dict.p​op(​"​key​") / dict.p​opi​tem()
back to tuple
m(r​emoves the last key
Concat​enate add tuple to tuple1 + tuple2 / tuple1 =+ tuple2 inserted))
a tuple
using del del dict("k​ey")
Lists inside a tuple are tuple = (["v​alu​e1",​"​val​ue2​"], item2,
del can delete the del dict
changeable item3)
dictionary completely
count() returns the tuple.c​ount() / tuple.c​ou​nt(​'va​lue')
clear empties the dict.c​lear() or dict = {}
number of items
dictionary
index() finds the item and tuple.i​​n​de​​x('​​va​lue')
Copy dict = dict2 / dict2 = dict.c​opy() / dict2 =
return its index
dict(dict)
min() / max() / sum() tuple.m​in() tuple.m​ax() tuple.s​um()
items() dict.i​tems()
enumer​​at​e​(​index, value) for i, v in enumer​​at​e​(​tuple): /n "{i} : {v}'
keys() dict.k​eys()
for loop for x in tuple:
values() dict.v​alues()
through index for x in range(​​le​n​(​tup​le)):
for loop for keys in dict:
while loop while x <= len(tu​ple): /n i+=1
keys for keys in dict.k​eys():
list compre​​eh​e​nsion [print[x] for x in tuple]
values for values in dict.v​alu​es():
keys and values for keys, values in dict.i​tems()

By corisco Published 7th November, 2022. Sponsored by Readable.com


cheatography.com/corisco/ Last updated 5th November, 2022. Measure your website readability!
Page 3 of 3. https://readable.com

You might also like