260 likes | 353 Views
CS 177 Week 9 Recitation Slides. Creating and Modifying Text. ANY QUESTIONS?. Text and String. Like sound, text is usually processed in an array —a long line of characters Strings are defined with quote marks: Single quotes ‘ my string ‘ Double quotes “ my string “
E N D
CS 177 Week 9 Recitation Slides Creating and Modifying Text
Text and String • Like sound, text is usually processed in an array—a long line of characters • Strings are defined with quote marks: • Single quotes ‘ my string ‘ • Double quotes “ my string “ • Triple quotes “““ my string “““ • Question: When triple quotes are used?
Encoding for Strings • Strings are just arrays of characters • Characters are either encoded in ASCII (single byte) or unicode (2 bytes). • ord(char): returns the ASCI value of char. • Example: >>> str = “JES" >>> for char in str: ... print ord(char) 74 69 83
Backslash escape “\b”: backspace “\n”: newline “\t” : tab “\uXXXX”: unicode of XXXX
What is the output? >>> print "Good\nMorning“ >>>print "Bo\bok“ >>> print "Good\tMorning“
Getting Parts of a String • string[n] gives you the nth character in the string • string[n:m] gives you the nth up to (but not including) the mth character. • string[0:len(string)] is the whole string • Example: • >>> str = "mathematics“ • >>> print str[4] • e • >>> print str[6] • a
Example continued • >>> print str[:4] • math • >>> print str[4:] • ematics • >>> print str[:] • mathematics
String Methods find(findstring) and find(findstring,start) and find(findstring,start,end) finds the findstring in the object string and returns the index number where the string starts. You can tell it what index number to start from, and even where to stop looking. It returns -1 if it fails. There is also rfind(findstring) (and variations) that searches from the end of the string toward the front.
Example >>> str = "one and one“ >>> str.find("ne") 1 >>> str.find("ne", 5) 9 >>> str.find("on", 7) 8 >>> str.rfind("o") 8
More String Methods swapcase() makes all upper->lower and vice versa isalpha() returns true if the string is not empty and all letters isdigit() returns true if the string is not empty and all numbers replace(char1, char 2) replace every char1 with char 2
Examples >>> str= "Purdue University" >>> str.swapcase() 'pURDUE uNIVERSITY‘ >>> str = "computer science" >>> str.upper() 'COMPUTER SCIENCE' >>> str = "computer AND books" >>> str.upper() 'COMPUTER AND BOOKS'
Examples continued >>> str.lower() 'computer and books' >>> str.title() 'Computer And Books‘ >>> str="123" >>> str.isdigit() 1
Examples continued >>> str = "computer" >>> str.isalpha() 1 >>> str = "data" >>> str.replace("a","z") 'dztz'
Lists • Lists can contain strings, numbers, even other lists. Example: >>> myList = ["X", "B", 3, "A", 1] >>> print myList ['X', 'B', 3, 'A', 1]
List methods • append(something) puts something in the list at the end. • remove(something) removes something from the list … if it’s there. • sort() puts the list in alphabetical order • reverse() reverses the list • count(something) tells you the number of times that something is in the list. • max() and min() are methods (we’ve seen them before) that take a list as input and give you the maximum and minimum value in the list.
Examples >>> myList = ["X", "B", 3, "A", 1] >>> print myList ['X', 'B', 3, 'A', 1] >>> myList.append("F") >>> print myList ['X', 'B', 3, 'A', 1, 'F'] >>> myList.remove("B") >>> print myList ['X', 3, 'A', 1, 'F']
Examples continued >>> myList.sort() >>> print myList [1, 3, 'A', 'F', 'X'] >>> myList.reverse() >>> print myList ['X', 'F', 'A', 3, 1] >>> myList.count("A") 1
Examples continued >>> max(myList) 'X' How? Max returns the element with the maximum ASCII value. Looking up the ASCII values on the list, X value is 88 which is greater than all of the elements. >>> min(myList) 1
Using lists to represent trees >>> tree = [["Leaf1","Leaf2"],[["Leaf3"],["Leaf4"],"Leaf5"]] >>> print tree [['Leaf1', 'Leaf2'], [['Leaf3'], ['Leaf4'], 'Leaf5']] >>> print tree[0] ['Leaf1', 'Leaf2'] >>> print tree[1] [['Leaf3'], ['Leaf4'], 'Leaf5'] >>> print tree[1][0] ['Leaf3'] >>> print tree[1][1] ['Leaf4'] >>> print tree[1][2] Leaf5 Leaf5 Leaf1 Leaf3 Leaf4 Leaf2 The Point: Lists allow us to represent complex relationships, like trees
Open File • Files can be opened for: • Read Text (rt) • Write Text (wt) • Read or write bytes (rb) In the command you specify the reason how you open your file: open(filename,how)
File Methods • open() returns a file object that you use to manipulate the file • Example: file=open(“myfile”,”wt”) • file.read() reads the whole file as a single string. • file.readlines() reads the whole file into a list where each element is one line. • read() and readlines() can only be used once without closing and reopening the file. • file.write(something) writes something to the file • file.close() closes the file—writes it out to the disk, and won’t let you do any more to it without re-opening it.
Searching Phonebook Create Phonebook def phonebook(): return """ Mary:893-0234:Realtor: Fred:897-2033:Boulder crusher: Barney:234-2342:Professional bowler:"""
Split the Entries in Phonebook split by line split elements in each line def phones(): phones = phonebook() phonelist = phones.split('\n') newphonelist = [] for list in phonelist: newphonelist = newphonelist + [list.split(":")] return newphonelist
Find People in Phonebook def findPhone(person): for people in phones(): if people[0] == person: print "Phone number for",person,"is",people[1] >>>findPhone(“Mary”) Phone number for Mary is 893-0234