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.

74 Chapter 8. StringsIf the first index is greater than or equal to the second the result is an empty string, represented bytwoquotation marks:>>> fruit = 'banana'>>> fruit[3:3]''An empty string contains no characters and has length 0, but other than that, it is the same as anyother string.Exercise 8.3 Given thatfruitisastring,what doesfruit[:] mean?8.5 Stringsare immutableItistemptingtousethe[]operatorontheleftsideofanassignment,withtheintentionofchangingacharacter inastring. For example:>>> greeting = 'Hello, world!'>>> greeting[0] = 'J'TypeError: object does not support item assignmentThe “object” in this case is the string and the “item” is the character you tried to assign. For now,an object is the same thing as a value, but we will refine that definition later. An item is one of thevalues inasequence.The reason for the error is that strings are immutable, which means you can’t change an existingstring. The best you can do iscreate anew stringthat isavariation on theoriginal:>>> greeting = 'Hello, world!'>>> new_greeting = 'J' + greeting[1:]>>> print new_greetingJello, world!Thisexampleconcatenatesanewfirstletterontoasliceofgreeting. Ithasnoeffectontheoriginalstring.8.6 SearchingWhat does the following function do?def find(word, letter):index = 0while index < len(word):if word[index] == letter:return indexindex = index + 1return -1In a sense, find is the opposite of the [] operator. Instead of taking an index and extracting thecorresponding character, it takes a character and finds the index where that character appears. If thecharacter isnot found, the function returns-1.

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

Saved successfully!

Ooh no, something went wrong!