http://www.cs.cornell.edu/courses/cs1110/2019sp 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]
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 2
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” 3
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” 4
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” 5
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” 6
Other Things We Can Do With Strings Operator in: s 1 in s 2 Built-in Function len : len(s) § Value is # of chars in s • Tests if s 1 “a part of” § 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’ 7 False >>>
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 8 'bbb'
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) 9
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 10 other way…’)
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 11
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' 12
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 13 See Python Docs for more
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 14
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) 15
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 16
String Extraction Puzzle >>> second('cat, dog, mouse, lion’) def second(thelist): """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 17
String Extraction Fix >>> second('cat, dog, mouse, lion’) def second(thelist): """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 18
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 19
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 ) 20
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 21 >>> >>>
unexpected printing courtesy of: Python Interactive Mode • executes both statements and expressions • if expression: 1. evaluates 2. prints value (if one exists) >>> 2+2 evaluates (performs addition) prints value (4) 4 >>> return_plus(2) evaluates (makes function call, gets return value) prints value (3) 3 >>> 22
Recommend
More recommend