1StringsStrings• A string is a series of characters• Characters can be referenced by usingbrackets• The first character is at position 0mystring = “the”letter = mystring[2] #letter becomes ‘e’tmystringh e0 1 2length• The len function returns the length of a stringmystring=“bob”len(mystring) #3len(“adam”) #4length=len(mystring)last = mystring[len-1] #retrieves last charfor loopsmystring = "CS is cool!"for c in mystring: print cindex=0while index < len(mystring):print mystring[index]index += 1Exercises1. Write a for or while loop to print a stringbackwardsSlices• Select a segment of a string• Specify [start:end]– include start but do not include end– if you do not specify start slice starts from thebeginning– if you do not specify end slices goes to endmystring=“CS is cool”print mystring[6:10]print mystring[2:7]print mystring[:4]print mystring[:]2String Comparison/in• == tests to see if strings are the same• >, < compares strings alphabetically• The in operator tests whether a given characterappears in a given string– ‘c’ in “chocolate” #true– ‘z’ in “chocolate” #falseImmutability• Strings are immutable– they cannot be changedstring module• Contains useful methods for stringshttp://docs.python.org/lib/string-methods.html• Dot notation allows us to call a method ona string objectimport stringmystring=“adam”string.find(mystring, “a”) #returns index of first instance foundmystring=“CS is cool”mystring.split() #result [‘CS’,’is’,’cool’]newstring = mystring.replace(“CS”, “Econ”)Exercises1. Write a program that prompts the userfor two strings and determines thenumber of two-character sequences thatappear in both the first and secondstrings. Exclude spaces in yourcomparison.• “CS is cool” “the old cow” would have twomatches “co” for “cool” and “cow” and “ol”for “cool” and
View Full Document