Lecture 7 Strings, Dictionaries and Sets
Lecture 7 Strings, Dictionaries and Sets
Programming Principles
Lecture 7: Strings, Dictionaries and Sets
This Lecture
• Strings
– Recap of strings
– String methods for testing, searching and manipulating
– Chaining methods
– Strings in other languages
# you can use string methods directly on strings, not just variables
str2 = 'Leonardo\nDonatello\nRaphael\nMichelangelo'
str3 = ', '.join(lst) # put ', ' between every item in the list
'Leonardo, Donatello, Raphael, Michelangelo'
str3.split(', ') # split the string into a list using ', '
['Leonardo', 'Donatello', 'Raphael', 'Michelangelo']
“Chaining” Methods
– Ideally, the user enters the data how you expect it:
Enter unit codes with commas between: CSP1150, CSG1132, CSI1241
units = val.split(', ') # result: ['CSP1150', 'CSG1132', 'CSI1241']
• (note that there is a space at the start and end of the input)
“Chaining” Methods
Enter unit codes with commas between: CSP 1150, CSG 1132 , csi1241,
units = val.split(', ') # result: [' CSP 1150', ' CSG 1132 ', 'csi1241', '']
① ' CSP 1150, CSG 1132 , csi1241, ' ② ' CSP 1150, CSG 1132 , CSI1241, '
③ 'CSP1150,CSG1132,CSI1241,' ④ 'CSP1150,CSG1132,CSI1241'
⑤ ['CSP1150', 'CSG1132', 'CSI1241']
“Chaining” Methods
faxes = {} # creates empty dictionary (that you can add items to)
– Note that since dictionaries are not ordered, the order that the
items appear in is random/arbitrary – it is not a “sequence”
phones[0]
KeyError: 0
phones['Brett']
KeyError: 'Brett'
– KeyError is raised if you try to refer to a key that does not exist
Adding, Changing and Removing Dictionary Items
items() Returns a live list of tuples of all key-value pairs in the dictionary.
pop(key, default) Like “get()”, but also deletes the item after returning the value.
• PHP uses “=>” instead of “:” between key and value, and
has a “foreach” loop to iterate through the items:
$phones = array('Greg' => 6283, 'Justin' => 6174, 'Phil' => 6427); PHP
foreach($phones as $key => $value)
{
echo "$key - $value\n";
}
set2 = set('abracadabra') # can only pass one item to turn into a set
{'b', 'r', 'c', 'd', 'a'}
– Curly braces will create a set if you don’t specify keys, and a
dictionary if you do
– If you use “set()”, you can only pass one value and it will be
broken down into a set of unique values