You are on page 1of 5

More with Strings, Lists,

and Dictionaries
Strings
Operator Example Result Name Description
+ hello + world hello world Concatenation Joins two strings together
* abc * 3 abcabcabc Repetition Repeats the string
[i] abc[1] b Index Returns the character at position i
[i:j] abcdef[0:2] ab Slice Returns the substring from i to j-1
len() len(abc) 3 Length Determines the length of the string
in bc in abc True In Determines whether one string contains
another
not in bc not in abc False Not in Determines whether one string does not
contain another
Strings
Method Use Explanation
count astring.count(item) Returns the number of occurrences of item in astring.
index astring.index(item) Returns the index of the first occurrence of item in
astring, or an error if not found
find astring.find(item) Returns the index of the first occurrence of item in
astring, or -1 if not found.
replace astring.replace(old,new) Replaces all occurrences of old substring with new
substring in astring
split astring.split() Returns a list of substrings of astring. The original
string is divided at each space.
split astring.split(item) Returns a list of substrings of astring. The original
string is divided at each appearance of item.
Lists
Method Use Explanation
append alist.append(item) Adds a new item to the end of a list
insert alist.insert(i,item) Inserts an item at the ith position in a list
pop alist.pop() Removes and returns the last item in a list
pop alist.pop(i) Removes and returns the ith item in a list
sort alist.sort() Modifies alist to be sorted
reverse alist.reverse() Modifies alist to be in reverse order
index alist.index(item) Returns the index of the first occurrence of item
count alist.count(item) Returns the number of occurrences of item
remove alist.remove(item) Removes the first occurrence of item
Dictionaries
Method Use Explanation
keys adict.keys() Returns a dict_keys object of keys in the dictionary
values adict.values() Returns a dict_values object of values in the dictionary
items adict.items() Returns a dict_items object of key-value tuples
get adict.get(k) Returns the value associated with k, None otherwise.
get adict.get(k,alt) Returns the value associated with k, alt otherwise
in key in adict Returns True if the key is in the dictionary, False otherwise
not in key not in adict Returns True if key is not in the dictionary, False otherwise
index adict[Key] Returns the value associates with key
del del adict[key] Removes the entry from the dictionary

You might also like