Python 3

home

Introduction to Python

davidbpython.com




Data Parsing & Extraction: List Operations and String Slicing


lists and list subscripting

Subscripting allows us to select individual items from a list.


fields = ['jw234', 'Joe', 'Wilson', 'Smithtown', 'NJ', '2015585894']

var = fields[0]           # 'jw234', 1st item
var2 = fields[4]          # 'NJ', 3rd item
var3 = fields[-1]         # '2015585894' (-1 means last item)


Ex. 4.5






list slicing

Slicing allows us to select multiple items from a list.


letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
first_four = letters[0:4]
print(first_four)                     # ['a', 'b', 'c', 'd']

# no upper bound takes us to the end
print(letters[5:])                    # ['f', 'g', 'h']

Here are the rules for slicing:






string slicing

Slicing a string selects characters the way that slicing a list selects items.


mystr = '20140313 15:33:00'
year =  mystr[0:4]               # '2014'
month = mystr[8:10]              # '03'
day =   mystr[10:12]             # '13'

Again, please review the rules for slicing:


now can go back to 4.3, 4.4






the IndexError exception

An IndexError exception indicates use of an index for a list item that doesn't exist.


mylist = ['a', 'b', 'c']

print(mylist[5])            # IndexError:  list index out of range

Since mylist does not contain a sixth item (i.e., at index 5), Python tells us it cannot complete this operation.





[pr]