CS 1110: Introduction to Computing Using Python Lecture 5 Strings [Andersen, Gries, Lee, Marschner, Van Loan, White]
Today • Return to the string ( str ) type Learn several new ways to use strings • See more examples of functions Particularly functions with strings • Learn the difference between print and return 2/9/17 Strings 2
Strings are Indexed • 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” 2/9/17 Strings 3
Strings are Indexed • 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” 2/9/17 Strings 4
Other Things We Can Do With Strings • Operation in : s 1 in s 2 • Function len: len(s) Tests if s 1 “a part of” s 2 Value is # of chars in s Say s 1 a substring of s 2 Evaluates to an int Evaluates to a bool • Examples : • Examples : s = 'abracadabra' s = 'abracadabra’ 'a' in s True len(s) 11 True 'cad' in s len(s[1:5]) 4 False 'foo' in s s[1:len(s)-1] 'bracadabr' 2/9/17 Strings 5
Defining a String Function >>> middle('abc') 'b' >>> middle('aabbcc') 'bb' >>> middle('aaabbbccc') 'bbb' 2/9/17 Strings 6
Defining a String Function def middle(text): 1. Add string parameter """Returns: middle 3 rd of text 2. Add return at end Param text: a string with Set to be “result” for now length divisible by 3""" 3. Work in reverse # Get length of text Set subgoals size = len(text) Identify needed operations # Start of middle third start = size/3 Store results in variables # End of middle third Assign on previous lines end = 2*size/3 # Get the text result = text[start:end] # Return the result return result 2/9/17 Strings 7
Defining a String Function def middle(text): >>> middle('abc') """Returns: middle 3 rd of text 'b' Param text: a string with length divisible by 3""" >>> middle('aabbcc') 'bb' # Get length of text size = len(text) >>> middle('aaabbbccc') # Start of middle third 'bbb' start = size/3 # End of middle third end = 2*size/3 # Get the text result = text[start:end] # Return the result return result 2/9/17 Strings 8
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() - converts to upper case s = 'Hello World' s.upper() 'HELLO WORLD' s[1:5].upper() 'ELLO' 'methods'.upper() 'METHODS' 'cs1110'.upper() 'CS1110' 2/9/17 Strings 9
Examples of String Methods • s 1 .index(s 2 ) • s = 'abracadabra' Position of the first • s.index('a') 0 instance of s 2 in s 1 • s.index('rac') 2 • s.count('a') 5 • s 1 .count(s 2 ) 2 Number of times s 2 • s.count('b') appears inside of s 1 0 • s.count('x') 'a b' • ' a b '.strip() • s.strip() A copy of s with white- space removed at ends See Python Docs for more 2/9/17 Strings 10
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' # 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 the result return substr[:end] 2/9/17 Strings 11
HANDOUT IS WRONG! 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 = s.index('(') 'A' # Store part AFTER paren tail = s[start+1:] # Find the close parenthesis end = tail.index(')') # Return the result return tail[:end]
String Extraction Puzzle def second(thelist): >>> second('cat, dog, mouse, lion') """Returns: second word in a list 'dog' of words separated by commas >>> second('apple, pear, banana') and spaces. 'pear' Ex: second('A, B, C') => 'B' Param thelist: a list of words with at least two commas Where is the error? 1 start = thelist.index(',') A: Line 1 2 tail = thelist[start+1:] B: Line 2 3 end = tail.index(',') C: Line 3 4 result = tail[:end] D: Line 4 5 return result E: There is no error 2/9/17 Strings 13
String Extraction Puzzle def second(thelist): >>> second('cat, dog, mouse, lion') """Returns: second word in a list 'dog' of words separated by commas >>> second('apple, pear, banana') and spaces. 'pear' Ex: second('A, B, C') => 'B' Param thelist: a list of words with at least two commas 1 start = thelist.index(',') tail = thelist[start+2:] 2 tail = thelist[start+1:] 3 end = tail.index(',') 4 but what if there are multiple spaces? result = tail[:end] 5 return result result = tail[:end].strip() 2/9/17 Strings 14
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 \' Delineate with “other quote” single 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 2/9/17 Strings 15
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""" print 'Hello '+n+'!' Displays these strings on the screen print 'How are you?' No assignments or return The call frame is EMPTY 2/9/17 Strings 16
Procedures vs. Fruitful Functions Procedures Fruitful Functions • Functions that do something • Functions that give a value • Call them as a statement • Call them in an expression • Example: • Example: greet('Prof. Andersen') x = round(2.56,1) 2/9/17 Strings 17
print vs. return • Sometimes appear to have similar behavior def print_plus(n): def return_plus(n): print n+1 return n+1 >>> print_plus(2) >>> return_plus(2) 3 3 >>> >>> 2/9/17 Strings 18
print vs. return Print Return • Displays a value on the screen • Sends a value from a function Used primarily for testing call frame back to the caller Not useful for calculations Important for calculations But does not display anything 2/9/17 Strings 19
Python Interactive Shell >>> • executes both statements and expressions • if expression , prints value (if it exists) def return_plus(n): >>> 2+2 return n+1 4 prints to screen >>> >>> return_plus(2) 3 prints to screen >>> 2/9/17 Strings 20
So why do these behave similarly? def print_plus(n): def return_plus(n): print n+1 return n+1 >>> print_plus(2) >>> return_plus(2) 3 3 >>> >>> 2/9/17 Strings 21
return def return_plus(n): return n+1 call frame Python Interactive Shell expression return_plus >>> return_plus(2) return_plus(2) 3 RETURN 3 n 2 creates evaluates return s value Shell automatically prints expression value 2/9/17 Strings 22
print def print_plus(n): print n+1 call frame Python Interactive Shell expression print_plus >>> print_plus(2) print_plus(2) 3 n 2 creates evaluates print s value directly to the Python Interactive Shell Shell tries to print expression value but there is no value (because no return !) 2/9/17 Strings 23
print vs. return Print Return def print_plus(n): def return_plus(n): print n+1 return n+1 >>> x = print_plus(2) >>> x = return_plus(2) 3 >>> >>> x x 3 Nothing here! 2/9/17 Strings 24
Recommend
More recommend