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.

Chapter 8Strings8.1 Astringis a sequenceA string is a sequence of characters. You can access the characters one at a time with the bracketoperator:>>> fruit = 'banana'>>> letter = fruit[1]The second statement selects character number 1 fromfruitand assigns ittoletter.The expression in brackets is called an index. The index indicates which character in the sequenceyou want (hence thename).But you might not get what you expect:>>> print letteraFormostpeople, thefirstletterof'banana'isb,nota. Butforcomputer scientists,theindexisanoffset fromthe beginning ofthe string,and the offsetof thefirst letteriszero.>>> letter = fruit[0]>>> print letterbSo b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the 2th(“two-eth”) letter.Youcanuseanyexpression,includingvariablesandoperators,asanindex,butthevalueoftheindexhas tobe an integer. Otherwiseyou get:>>> letter = fruit[1.5]TypeError: string indices must be integers

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

Saved successfully!

Ooh no, something went wrong!