lecture 5 strings
play

Lecture 5: Strings (Sections 8.1, 8.2, 8.4, 8.5, 1 st paragraph of - PowerPoint PPT Presentation

http://www.cs.cornell.edu/courses/cs1110/2020sp Lecture 5: Strings (Sections 8.1, 8.2, 8.4, 8.5, 1 st paragraph of 8.9) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Fan, D. Gries, L. Lee, S. Marschner, C. Van Loan,


  1. http://www.cs.cornell.edu/courses/cs1110/2020sp Lecture 5: Strings (Sections 8.1, 8.2, 8.4, 8.5, 1 st paragraph of 8.9) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Fan, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

  2. No-laptop front Announcements zone on your left ok • No laptop use stage right (your left) • We will use clickers, but not for credit. Therefore no need to register your clicker. • “Partner Finding Social” Tues Feb 4 th 5-6pm Gates Hall 3 rd floor Lounge (1xxx-2xxx courses) • Before next lecture, read Sections 4.9, 9.5 • To access video of lecture, log in using NetID and password “through Canvas”, but we don’t use Canvas otherwise. Course website is https://www.cs.cornell.edu/courses/cs1110/2020sp/ 2

  3. Today • More about the str type  New ways to use strings • More examples of functions  Functions with strings! • Learn the difference between print and return 3

  4. Strings are Indexed (Question 1) • s = 'abc d' • t = 'Hello all' 0 1 2 3 4 0 1 2 3 4 5 6 7 8 a b c d H e l l o a l l • Access characters with [] • What is t[3:6] ?  s[0] is 'a' A: 'lo a'  s[4] is 'd' B: 'lo'  s[5] causes an error C: 'lo '  s[0:2] is 'ab' (excludes c ) D: 'o '  s[2:] is 'c d' E: I do not know • Called “string slicing” 4

  5. Strings are Indexed (Solution 1) • s = 'abc d' • t = 'Hello all' 0 1 2 3 4 0 1 2 3 4 5 6 7 8 a b c d H e l l o a l l • Access characters with [] • What is t[3:6] ?  s[0] is 'a' A: 'lo a'  s[4] is 'd' B: 'lo'  s[5] causes an error CORRECT C: 'lo '  s[0:2] is 'ab' (excludes c ) D: 'o '  s[2:] is 'c d' E: I do not know • Called “string slicing” 5

  6. Strings are Indexed (Question 2) • s = 'abc d' • t = 'Hello all' 0 1 2 3 4 0 1 2 3 4 5 6 7 8 a b c d H e l l o a l l • Access characters with [] • What is t[:3] ?  s[0] is 'a' A: 'all'  s[4] is 'd' B: 'l'  s[5] causes an error C: 'Hel'  s[0:2] is 'ab' (excludes c ) D: Error!  s[2:] is 'c d' E: I do not know • Called “string slicing” 6

  7. Strings are Indexed (Solution 2) • s = 'abc d' • t = 'Hello all' 0 1 2 3 4 0 1 2 3 4 5 6 7 8 a b c d H e l l o a l l • Access characters with [] • What is t[:3] ?  s[0] is 'a' A: 'all'  s[4] is 'd' B: 'l'  s[5] causes an error CORRECT C: 'Hel'  s[0:2] is 'ab' (excludes c ) D: Error!  s[2:] is 'c d' E: I do not know • Called “string slicing” 7

  8. Other Things We Can Do With Strings Operator in: s 1 in s 2 Built-in Function len : len(s) • Tests if s 1 “a part of”  Value is # of chars in s (or a substring of) s 2  Evaluates to an int • Evaluates to a bool Examples : Examples : >>> s = 'abracadabra’ >>> s = 'abracadabra' >>> len(s) >>> 'a' in s 11 True >>> len(s[1:5]) >>> 'cad' in s 4 True >>> s[1:len(s)-1] >>> 'foo' in s 'bracadabr' False >>> 8

  9. Defining a String Function Important Questions: Want to write function 1. What are the parameters? middle , which returns the 2. What is the return value? middle 3 rd of a string (length 3. What goes in the body? divisible by 3). How we want it to behave: def middle(text): >>> middle('abc') 'b' ??? >>> middle('aabbcc') 'bb' >>> middle('aaabbbccc') return middle_third 'bbb' 9

  10. Steps to writing a program 1. Work an instance yourself 2. Write down exactly what you just did 3. Generalize your steps from 2 4. Test your steps 5. Translate to Code 6. Test program 7. Debug (if necessary) 10

  11. Steps to writing a program 1. Work an instance yourself 2. Write down exactly what you just did 3. Generalize your steps from 2 4. Test your steps 5. Translate to Code Too easy!! >>> middle('abc') middle_third = text[1] >>> middle('aabbcc') Still too easy!! middle_third = text[2:4] >>> middle ('It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way…') 11

  12. Definition of middle middle def middle(text): """Returns: middle 3 rd of text IMPORTANT: Paramtext: a string with Precondition requires length divisible by 3""" that arguments to middle have length divisible by 3. If not? Bad things could happen, and we blame the user (not the author) of the function. 12

  13. Definition of middle middle def middle(text): """Returns: middle 3 rd of text IMPORTANT: Paramtext: a string with Precondition requires length divisible by 3""" that arguments to middle have length # Get length of text divisible by 3. size = len(text) # Start of middle third If not? Bad things start2 = size//3 could happen, and we # End of middle third blame the user (not start3 = (2*size)//3 the author) of the # Get the substring middle_third = text[start2:start3] function. return middle_third 13

  14. Advanced String Features: Method Calls • Strings have some useful methods  Like functions, but “with a string in front” • Format : < string name > . <method name> ( x , y, …) • Example : upper() returns an upper case version >>> s = 'Hello World’ >>> s[1:5].upper() 'ELLO' >>> s.upper() >>> ‘scream'.upper() 'HELLO WORLD’ ‘SCREAM' >>> s >>> 'cs1110'.upper() 'Hello World’ 'CS1110' 14

  15. Examples of String Methods • s 1 .index(s 2 ) • s = 'abracadabra’  Returns position of the first 0 1 2 3 4 5 6 7 8 9 10 instance of s 2 in s 1 a b r a c a d a b r a  error if s 2 is not in s 1 • s.index('a') 0 • s 1 .count(s 2 ) • s.index('rac') 2  Returns number of times s 2 • s.count('a') 5 appears inside of s 1 • s.count('b') 2 • s.strip() • s.count('x') 0  Returns a copy of s with • ' a b '.strip() 'a b' white-space removed at ends 15 See Python Docs for more

  16. String Extraction Example def firstparens(text): >>> s = 'One (Two) Three' """Returns: substring in () >>> firstparens(s) Uses the first set of parens 'Two' Param text: a string with ()""" >>> t = '(A) B (C) D' >>> firstparens(t) 'A' 16

  17. String Extraction, Round 1 def firstparens(text): >>> s = 'One (Two) Three' """Returns: substring in () >>> firstparens(s) Uses the first set of parens 'Two' Param text: a string with ()""" >>> t = '(A) B (C) D' # Find the open parenthesis >>> firstparens(t) start = text.index('(') 'A' # Find the close parenthesis end = text.index(‘)’) inside = text[start+1:end] return inside 17

  18. Steps to writing a program 1. Work an instance yourself 2. Write down exactly what you just did 3. Generalize your steps from 2 4. Test your steps 5. Translate to Code Think of all the corner cases 6. Test program What could possibly go wrong? 7. Debug (if necessary) 18

  19. String Extraction, Round 2 def firstparens(text): >>> s = 'One (Two) Three' """Returns: substring in () >>> firstparens(s) Uses the first set of parens 'Two' Param text: a string with ()""" >>> t = '(A) B (C) D' # Find the open parenthesis >>> firstparens(t) start = text.index('(') 'A' # Store part AFTER paren substr = text[start+1:] # Find the close parenthesis end = substr.index(')') inside = substr[:end] return inside 19

  20. String Extraction Puzzle def second(thelist): """Returns: second word in a list of words separated by commas, with any leading or trailing spaces from the second word removed Ex: second('A, B, C') => 'B' Paramthelist: a list of words with at least two commas """ Is there an error? start = thelist.index(',') 1 tail = thelist[start+1:] 2 A: Yes, Line 1 end = tail.index(',') 3 B: Yes, Line 2 result = tail[:end] 4 C: Yes, Line 3 return result 5 D: Yes, Line 4 E: There is no error 20

  21. String Extraction Puzzle def second(thelist): >>> second('cat, dog, mouse, lion') """Returns: second word in a list expecting: 'dog' get: ' dog' of words separated by commas, with any leading or trailing spaces from the >>> second('apple, pear, banana') second word removed Ex: second('A, B, C') => 'B' expecting: 'pear' get: ‘ pear' Paramthelist: a list of words with at least two commas """ Is there an error? start = thelist.index(',') 1 tail = thelist[start+1:] 2 A: Yes, Line 1 end = tail.index(',') 3 B: Yes, Line 2 result = tail[:end] 4 C: Yes, Line 3 return result 5 D: Yes, Line 4 E: There is no error 21

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend