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.

72 Chapter 8. Strings8.2 lenlenisabuilt-infunction that returnsthe number of characters inastring:>>> fruit = 'banana'>>> len(fruit)6To get the lastletter ofastring,you might be tempted totrysomething likethis:>>> length = len(fruit)>>> last = fruit[length]IndexError: string index out of rangeThe reason for the IndexError is that there is no letter in ’banana’ with the index 6. Since westarted counting at zero, the six letters are numbered 0 to 5. To get the last character, you have tosubtract 1 fromlength:>>> last = fruit[length-1]>>> print lastaAlternatively, you can use negative indices, which count backward from the end of the string. Theexpressionfruit[-1]yields the lastletter,fruit[-2]yields thesecond tolast,and soon.8.3 Traversalwith aforloopA lot of computations involve processing a string one character at a time. Often they start at thebeginning, select each character in turn, do something to it, and continue until the end. This patternof processing iscalled atraversal. One way towriteatraversal iswithawhileloop:index = 0while index < len(fruit):letter = fruit[index]print letterindex = index + 1This loop traverses the string and displays each letter on a line by itself. The loop condition isindex < len(fruit), so when index is equal to the length of the string, the condition is false,and the body of the loop is not executed. The last character accessed is the one with the indexlen(fruit)-1,which isthe lastcharacter inthe string.Exercise 8.1 Write a function that takes a string as an argument and displays the letters backward,one per line.Another way towriteatraversal iswithaforloop:for char in fruit:print charEach time through the loop, the next character in the string is assigned to the variable char. Theloop continues untilno characters are left.

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

Saved successfully!

Ooh no, something went wrong!