12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

10.9. Listsand strings 95>>> t = ['a', 'b', 'c', 'd', 'e', 'f']>>> del t[1:5]>>> print t['a', 'f']As usual, thesliceselects allthe elements up to,but not including, the second index.10.9 Listsand stringsA string is a sequence of characters and a list is a sequence of values, but a list of characters is notthesame as astring. To convert from astringtoalistof characters, you can uselist:>>> s = 'spam'>>> t = list(s)>>> print t['s', 'p', 'a', 'm']Becauselististhenameofabuilt-infunction,youshouldavoidusingitasavariablename. Ialsoavoidlbecause itlooks too much like1. Sothat’s why I uset.The list function breaks a string into individual letters. If you want to break a string into words,you can use thesplitmethod:>>> s = 'pining for the fjords'>>> t = s.split()>>> print t['pining', 'for', 'the', 'fjords']An optional argument called a delimiter specifies which characters to use as word boundaries. Thefollowing example uses a hyphen as adelimiter:>>> s = 'spam-spam-spam'>>> delimiter = '-'>>> s.split(delimiter)['spam', 'spam', 'spam']joinistheinverseofsplit. Ittakesalistofstringsandconcatenatestheelements. joinisastringmethod, soyou have toinvoke itonthe delimiter and pass thelistas aparameter:>>> t = ['pining', 'for', 'the', 'fjords']>>> delimiter = ' '>>> delimiter.join(t)'pining for the fjords'In this case the delimiter is a space character, so join puts a space between words. To concatenatestringswithout spaces, you can use theempty string,'', as adelimiter.10.10 Objectsand valuesIfweexecute theseassignment statements:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!