CS 177 Week 9 Recitation Slides

26
1 CS 177 Week 9 Recitation Slides Creating and Modifying Text

description

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 “ - PowerPoint PPT Presentation

Transcript of CS 177 Week 9 Recitation Slides

Page 1: CS 177 Week 9 Recitation Slides

1

CS 177 Week 9 Recitation Slides

Creating and Modifying Text

Page 2: CS 177 Week 9 Recitation Slides

2

ANY QUESTIONS?

Page 3: CS 177 Week 9 Recitation Slides

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?

3

Page 4: CS 177 Week 9 Recitation Slides

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 4

Page 5: CS 177 Week 9 Recitation Slides

Backslash escape

“\b”: backspace “\n”: newline “\t” : tab “\uXXXX”: unicode of XXXX

5

Page 6: CS 177 Week 9 Recitation Slides

What is the output?

>>> print "Good\nMorning“ >>>print "Bo\bok“ >>> print "Good\tMorning“

6

Page 7: CS 177 Week 9 Recitation Slides

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

7

Page 8: CS 177 Week 9 Recitation Slides

Example continued

>>> print str[:4] math >>> print str[4:] ematics >>> print str[:] mathematics

8

Page 9: CS 177 Week 9 Recitation Slides

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.

9

Page 10: CS 177 Week 9 Recitation Slides

Example

>>> str = "one and one“

>>> str.find("ne")

1

>>> str.find("ne", 5)

9

>>> str.find("on", 7)

8

>>> str.rfind("o")

8

10

Page 11: CS 177 Week 9 Recitation Slides

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

11

Page 12: CS 177 Week 9 Recitation Slides

Examples>>> str= "Purdue University"

>>> str.swapcase()

'pURDUE uNIVERSITY‘

>>> str = "computer science"

>>> str.upper()

'COMPUTER SCIENCE'

>>> str = "computer AND books"

>>> str.upper()

'COMPUTER AND BOOKS'

12

Page 13: CS 177 Week 9 Recitation Slides

Examples continued>>> str.lower()

'computer and books'

>>> str.title()

'Computer And Books‘

>>> str="123"

>>> str.isdigit()

1

13

Page 14: CS 177 Week 9 Recitation Slides

Examples continued

>>> str = "computer"

>>> str.isalpha()

1

>>> str = "data"

>>> str.replace("a","z")

'dztz'

14

Page 15: CS 177 Week 9 Recitation Slides

Lists Lists can contain strings, numbers, even other lists.

Example:

>>> myList = ["X", "B", 3, "A", 1]

>>> print myList

['X', 'B', 3, 'A', 1]

15

Page 16: CS 177 Week 9 Recitation Slides

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.

16

Page 17: CS 177 Week 9 Recitation Slides

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']

17

Page 18: CS 177 Week 9 Recitation Slides

Examples continued>>> myList.sort()

>>> print myList

[1, 3, 'A', 'F', 'X']

>>> myList.reverse()

>>> print myList

['X', 'F', 'A', 3, 1]

>>> myList.count("A")

1

18

Page 19: CS 177 Week 9 Recitation Slides

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

19

Element X F A 3 1

ASCII 88 70 65 51 49

Page 20: CS 177 Week 9 Recitation Slides

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

Leaf1

Leaf2

Leaf3Leaf4

Leaf5

The Point: Lists allow us to represent complex relationships, like trees

20

Page 21: CS 177 Week 9 Recitation Slides

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)

21

Page 22: CS 177 Week 9 Recitation Slides

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.

22

Page 23: CS 177 Week 9 Recitation Slides

Searching Phonebook

Create Phonebook

def phonebook():

return """

Mary:893-0234:Realtor:

Fred:897-2033:Boulder crusher:

Barney:234-2342:Professional bowler:"""

23

Page 24: CS 177 Week 9 Recitation Slides

Split the Entries in Phonebook

def phones():

phones = phonebook()

phonelist = phones.split('\n')

newphonelist = []

for list in phonelist:

newphonelist = newphonelist + [list.split(":")]

return newphonelist

24

split by line

split elements in each line

Page 25: CS 177 Week 9 Recitation Slides

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

25

Page 26: CS 177 Week 9 Recitation Slides

26

Final QUESTIONS???