Show Menu
Cheatography

strings, lists, tuples and dictionaries in python Cheat Sheet by

A cheatsheet for string, lists, tuples and dictionaries in python

STRINGS

Strings
string = "­wor­ds" or 'words'
conect
string­1+s­tring2
multiply
string*3
compare ('if' or 'if not')
string1 == string2 (or != or > or <)
check ('if or 'if not')
'subst­ring' in string
position
string[0] or string[-1] or string[x]
slicing
string­[st­art­:en­d:step]
 
string[:3] or string[1:]
 
string­[::-1] inverted

Slicing strings

slicing:
string­[st­art­:en­d:step]
from start to end
string­[2:5]
from start
string[:5]
to the end
string[2:]
jumping
string­[2:5:2]
negati­ve/­inv­erted
string­[::-1]

Modify strings

remove whites­paces before and after the string
string.st­rip()
or remove any 'chara­cters'
string.st­rip­('ch')
only before­(left) the string
string.ls­trip()
only after(­right) the string
string.rs­trip()
replace string
string.re­pla­ce(­"old value", "new value", counter)
counter is how many occurences from start, nothing is default and means every occurrence
use it to remove whites­paces inside the string
string.re­pla­ce(­" ", "­")
split strings create list from strings
string.sp­lit­(se­par­ato­r,m­axs­plit)
separator is optional, whitespace is default
string.sp­lit­(",")
maxsplit is optional, all occurr­ences is defaul­t(-1)
string.sp­lit­("-",1)
find string
string.fi­nd(­"­val­ue",­sta­rt,end)
find the first occurrence of a substring in a string
string.fi­nd(­"­sub­str­ing­")
start and end are optional
string.fi­nd(­"­sub­str­ing­"­,3,10)
returns the position of the substring
index and find are the same, except that when false find returns -1 and index returns error
string.in­dex­("su­bst­rin­g")
lowercase
string.lo­wer()
uppercase
string.up­per()
capitalize first char upper
string.ca­pit­alize()
title first char of each word upper
string.ti­tle()
join values of a list/d­ict­/tuple/ into string
' '.join­(list)
count the occurences of substring in a string
string.co­unt­('s­ubs­tring')

Format strings

str.format
'Hello, {} and {}'.fo­rma­t(s­tring, string2)
f-string (3.6+)
f'Hello, {string} and {string2}'
Integer numbers into strings*
f'Hello, {strin­g:_}'
'b' - binary
{string:b}
'c' - character (ASCII)
'Hello, {examp­le:­c}'.fo­rma­t(e­xample = 'String', ...)
'd' - decimal
'Hello, {0:d} and {1}.fo­rma­t(s­tri­ng,­str­ing2)
'o' - octal
{string:o}
'x' - hexade­cimal, lowercase
'Hello, {0.x} and {0:X}.f­or­mat­(st­ring)
'X' - hexade­cimal, uppercase
{string:X}
'n' - number, decimal in local language OS
{string:n}
Floati­ng-­point
f'{int­ege­r:f}' (6 standard)
round(a,2)
f'{int­ege­r:.2f}' (2 decimal digits)
'e' ou 'E' - scientific notation (6 standard)
{:e}.f­orm­at(999)
'E' - scientific notation (6 standard)
f'{999­:.3E}'
'g' precisão >=1, round digits p to signif­icant digit
{:g}.f­orm­at(­12.1­23­123­5843)
'n' - same as 'g', but local language OS
f'{12.1­23­123­584­3:n}'
'%' - multiply the number *100 and '%' after
f'{0.0­5:%}'
two digits before '.' and two after
'{:2.2­%}'.fo­rma­t(0.05)
Spacing
'<' left align / '^' center align / '>' right align
'{0:<1­6}'.fo­rma­t(s­tring) / f.'{st­rin­g:^16}' / {:>16}
number of digits
{:4)
whites­paces if the string has less than 16..
{strin­g:16}
choose char instead of whitespace
{*:16}

COLLEC­TIONS

List
collection which is ordered and change­able. Allows duplicate members.
Tuple
collection which is ordered and unchan­geable. Allows duplicate members.
Dictionary
collection which is ordered and change­able. No duplicate members.
Set
collection which is unordered, unchan­geable, and unindexed. No duplicate members.
 

LISTS

Lists
list = ["st­rin­g", "­str­ing­2", integer, Bool]
ordered, change­able, allow duplicates
list = [item1, item2, item3]
Lenght
len(list)
Access [start index includ­ed:end index not]
list[1] / list[-1], list[2:5], list[:5]
Check if Item exists
if "­ite­m" in list:
Change items
list[3] = "­new­_va­lue­"
range of items
list[2:5] = "­new­_va­lue­1", "­new­_va­lue­2"
insert­(in­dex­,value) without replacing any item
list.i­nse­rt(2, "­ite­m")
append() add item to the end
list.a­ppe­nd(­"­ite­m")
extend() add items from other list
list.e­xte­nd(­list2)
works with tuples also
list.e­xte­nd(­tuple)
remove() remove first matching value
list.r­emo­ve(­"­str­ing­")
pop() remove specified index, and returns it
list.p­op(1)
del() remove specified index
list.d­el(3)
clear() empties the list
list.c­lear()
sort() sort the list alphan­ume­rically
list.s­ort()
sort descending
list.s­ort­(re­ver­se=­True)
reverse() order
list.r­eve­rse()
copy() make a copy
list2 = list.c­opy()
or use list()
list3 = list(l­ist2)
Concat­enate Lists
list3 = list1 + list2
or use extend()
list.e­xte­nd(­list2)
count() returns the number of items*
list.c­ount() / list.c­oun­t('­value')
index() finds the item and return its index
list.i­nde­x('­value')
min() / max() / sum()
list.min() list.max() list.sum()
enumer­ate­(index, value)
for i, v in enumer­ate­(list): /n "{i} : {v}'
for loop
for x in list:
through index
for x in range(­len­(li­st)):
while loop
while x <= len(list): /n i+=1
list compre­ehe­nsion
[print[x] for x in list]

TUPLES

Tuples
tuple = ("va­lue­1", int, bool ,"va­lue­1")
are unordered, unchan­geable, allow duplicates
tuple = (item1,)
Lenght
len(tuple)
Access [start index includ­Â­ed:end index not]
tuple[1] / tuple[-1], tuple[­2:5], tuple[:5]
Check if Item exists
if "­Â­it­e­m­" in tuple:
Change items tuples are unchan­geable
list = list(t­uple)
convert tuple to list and back to tuple
tuple = tuple(­list)
Concat­enate add tuple to a tuple
tuple1 + tuple2 / tuple1 =+ tuple2
Lists inside a tuple are changeable
tuple = (["v­alu­e1",­"­val­ue2­"], item2, item3)
count() returns the number of items
tuple.c­ount() / tuple.c­ou­nt(­'va­lue')
index() finds the item and return its index
tuple.i­Â­n­de­­x('­Â­va­lue')
min() / max() / sum()
tuple.m­in() tuple.m­ax() tuple.s­um()
enumer­Â­at­e­(­index, value)
for i, v in enumer­Â­at­e­(­tuple): /n "{i} : {v}'
for loop
for x in tuple:
through index
for x in range(­Â­le­n­(­tup­le)):
while loop
while x <= len(tu­ple): /n i+=1
list compre­Â­eh­e­nsion
[print[x] for x in tuple]

DICTIO­NARIES

Dictio­naries
dict = {"ke­y":"v­alu­e", "­key­2":"v­alu­e2"}
ordered, change­Â­able, do not allow duplicates
dict={­"­key­1": bool,"k­ey2­"­:int, "­key­3": [list]}
dict cannot have same keys
Lenght
len(dict)
Access get the value of the "­key­"
value1 = dict["k­ey1­"]
dict.g­et(­"­key­"­,"return if not found")
value4 = dict.g­et(­"­key­4", "Not found")
List of Keys
x = dict.k­eys()
Check if key exists
if "­Â­ke­ys" in dict:
if values exists
if "­val­ue1­" in dict.v­alues()
Change values of a key
dict["k­ey"] = value
using update()
dict.u­pda­te(­{'k­ey'­:'v­alue'})
Add
dict["k­ey"] = value
also can use update()
dict.u­pda­te(­{'k­ey'­:'v­alue'})
Remove .pop or popite­m(r­emoves the last key inserted))
dict.p­op(­"­key­") / dict.p­opi­tem()
using del
del dict("k­ey")
del can delete the dictionary completely
del dict
clear empties the dictionary
dict.c­lear() or dict = {}
Copy
dict = dict2 / dict2 = dict.c­opy() / dict2 = dict(dict)
items()
dict.i­tems()
keys()
dict.k­eys()
values()
dict.v­alues()
for loop
for keys in dict:
keys
for keys in dict.k­eys():
values
for values in dict.v­alu­es():
keys and values
for keys, values in dict.i­tems()
               
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          More Cheat Sheets by corisco

          file handling in python Cheat Sheet