Lecture 5: Strings

Similar documents
Announcements For This Lecture

Announcements For This Lecture

Lecture 3. Strings, Functions, & Modules

Lecture 4: Defining Functions (Ch ) CS 1110 Introduction to Computing Using Python

Lecture 4: Defining Functions

Conditionals & Control Flow

Lecture 3: Functions & Modules

Module 3: Strings and Input/Output

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 10: Lists and Sequences

CS 1110: Introduction to Computing Using Python Lists and Sequences

Lecture 2: Variables & Assignments

Lecture 6: Specifications & Testing

CS 1110: Introduction to Computing Using Python Loop Invariants

Lecture 24: Loop Invariants

Lecture 4. Defining Functions

CS 1110, LAB 2: ASSIGNMENTS AND STRINGS

CS Lecture 19: Loop invariants

Lecture 17: Classes (Chapter 15)

Lecture 17: Classes (Chapter 15)

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

Lecture 11: Iteration and For-Loops

Not-So-Mini-Lecture 6. Modules & Scripts

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Getting Started Values, Expressions, and Statements CS GMU

Lecture 18: Using Classes Effectively (Chapter 16)

Iteration and For Loops

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

Lecture 4. Defining Functions

Lecture 12. Lists (& Sequences)

Lecture 9: Memory in Python

CMSC201 Computer Science I for Majors

Python Day 3 11/28/16

Announcements for this Lecture

CS 115 Lecture 4. More Python; testing software. Neil Moore

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

Python for Non-programmers

CS1110. Lecture 6: Function calls

CMSC201 Computer Science I for Majors

Lecture 4. Defining Functions

CS1110. Lecture 6: Function calls

Lecture 1. Types, Expressions, & Variables

PREPARING FOR PRELIM 1

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

Beyond Blocks: Python Session #1

Module 01: Introduction to Programming in Python

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Scripting Languages. Python basics

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Lecture 7: Objects (Chapter 15) CS 1110 Introduction to Computing Using Python

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

CS Lecture 26: Subclasses in Event-driven Programs A7 is out! Get started right away you need time to ask questions.

Comp Exam 1 Overview.

CSCA20 Worksheet Strings

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

BOOLEAN EXPRESSIONS CONTROL FLOW (IF-ELSE) INPUT/OUTPUT. Problem Solving with Computers-I

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

CS177 Recitation. Functions, Booleans, Decision Structures, and Loop Structures

Python Programming: Lecture 2 Data Types

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Strings and Testing string methods, formatting testing approaches CS GMU

CS 1301 Exam 1 Fall 2010

7. (2 pts) str( str( b ) ) str '4' will not compile (single, double, or triple quotes

Fundamentals of Programming. Lecture 1: Introduction + Basic Building Blocks of Programming

Booleans, Logical Expressions, and Predicates

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

CS 1110 Prelim 1 October 4th, 2012

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

Lecture 1. Course Overview, Python Basics

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

Built-in functions. You ve used several functions already. >>> len("atggtca") 7 >>> abs(-6) 6 >>> float("3.1415") >>>

CS 1110, LAB 3: STRINGS; TESTING

Lecture 1. Course Overview, Python Basics

4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4.

Lecture 20: While Loops (Sections 7.3, 7.4)

Ceng 111 Fall 2015 Week 7a

isinstance and While Loops

Notes on Chapter 1 Variables and String

CS 1110 Prelim 1 October 17th, 2013

Course Overview, Python Basics

Slicing. Open pizza_slicer.py

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

Manipulating Digital Information

Testing. UW CSE 160 Winter 2016

More on Strings Is Twitter Successful?

Strings are actually 'objects' Strings

Problem Solving With C++ Ninth Edition

Python 2 Conditionals and loops Matthew Egbert CS111

Here's an example of how the method works on the string "My text" with a start value of 3 and a length value of 2:

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES

Overview of List Syntax

Student Number: Instructor: Brian Harrington

DECOMPOSITION, ABSTRACTION, FUNCTIONS

CS116 - Module 3 - Strings and Input/Output

Accelerating Information Technology Innovation

UTORid: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell

Lecture 3. Functions & Modules

Transcription:

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]

Announcements Having trouble finding Piazza? New link on our webpage should help! 2

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

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

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

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

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

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

Defining a String Function Want to write function middle which returns the middle 3 rd of a string (length divisible by 3). Important Questions: 1. What are the parameters? 2. What is the return value? 3. What goes in the body? How we want it to behave: >>> middle('abc') 'b' >>> middle('aabbcc') 'bb' >>> middle('aaabbbccc') 'bbb' def middle(text):??? return middle_third 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 6. Test program 7. Debug (if necessary) 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 >>> middle('abc') >>> middle( aabbcc ) middle_third = text[1] middle_third = text[2:4] Too easy!! Still too easy!! >>> 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

Definition of middle def middle(text): """Returns: middle 3 rd of text Param text: a string with length divisible by 3""" # Get length of text size = len(text) # Start of middle third start2 = size//3 # End of middle third start3 = (2*size)//3 # Get the substring middle_third = text[start2:start3] return middle_third IMPORTANT: Precondition requires 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

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.upper() 'HELLO WORLD >>> s 'Hello World >>> s[1:5].upper() 'ELLO' >>> scream'.upper() SCREAM' >>> 'cs1110'.upper() 'CS1110' 13

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

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

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 Think of all the corner cases 7. Debug (if necessary) What could possibly go wrong? 16

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

String Extraction Puzzle 1 2 3 4 5 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' Param thelist: a list of words with at least two commas "" start = thelist.index(',') tail = thelist[start+1:] end = tail.index(',') result = tail[:end] return result >>> second('cat, dog, mouse, lion ) expecting: 'dog get: dog >>> second('apple,pear, banana') expecting: 'pear Where is the error? A: Line 1 B: Line 2 C: Line 3 D: Line 4 E: There is no error get: pear ' 18

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

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

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+'! ) print( How are you? ) Displays these strings on the screen No assignments or return (returns None) 21

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

unexpected printing courtesy of: Python Interactive Mode executes both statements and expressions if expression: 1. evaluates 2. prints value (if one exists) >>> 2+2 4 >>> return_plus(2) 3 >>> evaluates (performs addition) prints value (4) prints value (3) evaluates (makes function call, gets return value) 23

return_plus in action def return_plus(n): return n+1 call frame return_plus 1 n 2 Python Interactive Mode >>> return_plus(2) 3 >>> RETURN 3 1. Evaluates : makes function call, evaluates to return value 2. prints value 24

print_plus in action def print_plus(n): print(n+1) Python Interactive Mode >>> print_plus(2) 3 >>> call frame print_plus 1 n 2 RETURN NONE 1. Evaluates : makes function call, evaluates to return value 2. does not print value b/c it s NONE 25

hybrid_plus in action def hybrid_plus(n): print(n) return n+1 Python Interactive Mode >>> print_plus(2) 2 3 >>> call frame print_plus 1 n 2 RETURN 3 1. Evaluates : makes function call, evaluates to return value 2. print value 2 26

See the difference in the Python Tutor def print_plus(n): print(n+1) def return_plus(n): return n+1 x1 = print_plus(2) x2 = return_plus(2) print(x1) print(x2) http://cs1110.cs.cornell.edu/visualizer/#mode=edit 27

Exercise 1 Module Text Python Interactive Mode # module.py def foo(x): x = 1+2 x = 3*x >>> import module >>> print(module.x) A: 9 B: 10 C: 1 D: None E: Error What does Python give me? 28

Exercise 1, Solution Module Text Python Interactive Mode # module.py def foo(x): x = 1+2 x = 3*x >>> import module >>> print(module.x) A: 9 B: 10 C: 1 D: None E: Error What does Python give me? CORRECT 29

Exercise 2 Module Text Python Interactive Mode # module.py def foo(x): x = 1+2 x = 3*x y = foo(0) >>> import module >>> print(module.y) A: 9 B: 10 C: 1 D: None E: Error What does Python give me? 30

Exercise 2, Solution Module Text Python Interactive Mode # module.py def foo(x): x = 1+2 x = 3*x x = foo(0) >>> import module >>> print(module.x) A: 9 B: 10 C: 1 D: None E: Error What does Python give me? CORRECT 31

Exercise 3 Module Text Python Interactive Mode # module.py def foo(x): x = 1+2 x = 3*x return x+1 y = foo(0) >>> import module >>> module.y A: 9 B: 10 C: 1 D: None E: Error What does Python give me? 32

Exercise 3, Solution Module Text Python Interactive Mode # module.py def foo(x): x = 1+2 x = 3*x return x+1 y = foo(0) >>> import module >>> module.y A: 9 B: 10 C: 1 D: None E: Error What does Python give me? CORRECT 33

Exercise 4 1 2 3 Function Definition def foo(a,b): x = a y = b return x*y+y >>> x = 2 >>> foo(3,4) >>> x Function Call What does Python give me? A: 2 B: 3 C: 16 D: None E: I do not know 34

Exercise 4, Solution 1 2 3 Function Definition def foo(a,b): x = a y = b return x*y+y >>> x = 2 >>> foo(3,4) >>> x Function Call What does Python give me? A: 2 CORRECT B: 3 C: 16 D: None E: I do not know 35