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/2018sp 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. Gries, L. Lee, S. Marschner, C. Van Loan, W.


  1. http://www.cs.cornell.edu/courses/cs1110/2018sp 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. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

  2. Announcements Having trouble finding Piazza? • New link on our webpage should help! 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 • What is t[3:6] ? • Access characters with [] § 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 • What is t[3:6] ? • Access characters with [] § s[0] is 'a' A: 'lo a' § s[4] is 'd' B: 'lo' § s[5] causes an error C: 'lo ' CORRECT § 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 • What is t[:3] ? • Access characters with [] § 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 • What is t[:3] ? • Access characters with [] § s[0] is 'a' A: 'all' § s[4] is 'd' B: 'l' § s[5] causes an error C: 'Hel' CORRECT § 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 § Evaluates to an int (or a substring of) s 2 • 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’ 8 False >>>

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

  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 11 other way…’)

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

  13. 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' 13

  14. 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 14 See Python Docs for more

  15. 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(‘)’) return text[start+1:end] 15

  16. 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) 16

  17. 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(')’) return substr[:end] 17

  18. 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 ' Param thelist: a list of words with at least two commas ""” Where is the error? start = thelist.index(',') 1 tail = thelist[start+1:] 2 A: Line 1 end = tail.index(',') 3 B: Line 2 result = tail[:end] 4 C: Line 3 return result 5 D: Line 4 E: There is no error 18

  19. String Extraction Fix 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 ' Param thelist: a list of words with at least two commas ""” start = thelist.index(',') 1 tail = thelist[start+2:] #possible fix ?? tail = thelist[start+1:] 2 What if there are multiple ( or no! ) spaces? end = tail.index(',') 3 result = tail[:end].strip() #better fix! result = tail[:end] 4 return result 5 19

  20. String: Text as a Value • String are quoted characters Type : str § 'abc d' (Python prefers) § "abc d" (most languages) • How to write quotes in quotes? Char Meaning \' single quote § Delineate with “other quote” \" double quote § Example : " ' " or ' " ' \n new line § What if need both " and ' ? \t tab • Solution : escape characters \\ backslash § Format: \ + letter § Special or invisible chars 20

  21. Not All Functions Need a Return def greet(n): """Prints a greeting to the name n Parameter n: name to greet Precondition: n is a string""" Displays these print('Hello '+n+'!’) strings on the print(‘How are you?’) screen No assignments or return (returns None ) 21

  22. print return vs. • Displays a value on screen • Sends a value from a function call frame back to the caller • Used primarily for testing • Important for calculations • Not useful for calculations • Does not display anything def print_plus(n): def return_plus(n): ? print(n+1) return n+1 >>> print_plus(2) >>> return_plus(2) 3 3 22 >>> >>>

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