Announcements For This Lecture

Similar documents
Announcements For This Lecture

Lecture 5: Strings

Lecture 3. Strings, Functions, & Modules

Lecture 4. Defining Functions

Announcements for this Lecture

Conditionals & Control Flow

CS 1110: Introduction to Computing Using Python Lists and Sequences

Lecture 12. Lists (& Sequences)

Module 3: Strings and Input/Output

CMSC201 Computer Science I for Majors

Lecture 10: Lists and Sequences

PREPARING FOR PRELIM 1

CS 1110, LAB 2: ASSIGNMENTS AND STRINGS

CMSC201 Computer Science I for Majors

CS Lecture 19: Loop invariants

CS 1110 Prelim 1 October 17th, 2013

Lecture 5. Defining Functions

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

Accelerating Information Technology Innovation

Strings are actually 'objects' Strings

Lecture 8. Conditionals & Control Flow

CSCA20 Worksheet Strings

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

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

CS1 Lecture 3 Jan. 18, 2019

Accelerating Information Technology Innovation

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Lecture 7. Memory in Python

CS 1110 Prelim 2 November 14th, 2013

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

Slicing. Open pizza_slicer.py

Python Programming: Lecture 2 Data Types

Lecture 2: Variables & Assignments

[301] Strings. Tyler Caraza-Harter

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Programming for Engineers in Python. Recitation 1

Lecture 1. Types, Expressions, & Variables

More on Strings Is Twitter Successful?

6. Data Types and Dynamic Typing (Cont.)

Overview of List Syntax

CSC A20H3 S 2011 Test 1 Duration 90 minutes Aids allowed: none. Student Number:

CS 1110 Prelim 1 October 15th, 2015

Scripting Languages. Python basics

PHP. Interactive Web Systems

Compound Data Types 1

Python for Non-programmers

Lecture 11: Iteration and For-Loops

Programming for Engineers in Python. Autumn

Lecture 13. For-Loops

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

ECS15, Lecture 13. Midterm solutions posted. Topic 4: Programming in Python, cont. Staying up to speed with Python RESOURCES. More Python Resources

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

Which of the following expressions has the type int list?

Lists, loops and decisions

UNIVERSITÀ DI PADOVA. < 2014 March >

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Built-in Types of Data

Chapter 10: Creating and Modifying Text Lists Modules

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

UNIVERSITY OF TORONTO SCARBOROUGH. December 2017 EXAMINATIONS. CSCA20H3 Duration 3 hours. Examination Aids: Instructor: Bretscher

COMP1730/COMP6730 Programming for Scientists. Strings

Lecture 13. For-Loops

CS Prelim 1 Review Fall 2017

Python I. Some material adapted from Upenn cmpe391 slides and other sources

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

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

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

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Types, lists & functions

University of Texas at Arlington, TX, USA

CS1 Lecture 3 Jan. 22, 2018

String Processing CS 1111 Introduction to Programming Fall 2018

String Computation Program

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

Beyond Blocks: Python Session #1

Ceng 111 Fall 2015 Week 7a

S206E Lecture 19, 5/24/2016, Python an overview

Stacks. Revised based on textbook author s notes.

Lecture 19. Operators and Abstraction

Problem Solving With C++ Ninth Edition

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

CS 1110: Introduction to Computing Using Python Loop Invariants

Student Number: Instructor: Brian Harrington

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Python Tutorial. Day 1

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Python 1: Intro! Max Dougherty Andrew Schmitt

CS Prelim 1 Review Fall 2013

Should you know scanf and printf?

Introduction to Python

Python language: Basics

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Comp Exam 1 Overview.

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS )

Lecture 2 Tao Wang 1

Transcription:

Lecture 4 Strings

Announcements For This Lecture Chapter 8 Readings 8.1, 8.2, 8.4, 8.5 Avoid for-loop sections Next Lab More expression tables Testing functions Assignment 1 Will post it on Monday Need one more lecture Due Thu, Sep. 22 nd Lab 4 gives time to work Revise until correct Can work in pairs Submit one for both 9/6/16 Strings 2

Purpose of Today s Lecture Return to the string (str) type Saw it the first day of class Learn all of the things we can do with it See more examples of functions Particularly functions with strings Learn the difference between Procedures and fruitful functions print and return statements 9/6/16 Strings 3

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 9/6/16 Strings 4

String are Indexed s = 'abc d' s = '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 s[3:6]? A: 'lo a' B: 'lo' C: 'lo ' D: 'o ' E: I do not know 9/6/16 Strings 5

String are Indexed s = 'abc d' s = '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 s[3:6]? A: 'lo a' B: 'lo' C: 'lo ' CORRECT D: 'o ' E: I do not know 9/6/16 Strings 6

String are Indexed s = 'abc d' s = '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 s[:4]? A: 'o all' B: 'Hello' C: 'Hell' D: Error! E: I do not know 9/6/16 Strings 7

String are Indexed s = 'abc d' s = '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 s[:4]? A: 'o all' B: 'Hello' C: 'Hell' CORRECT D: Error! E: I do not know 9/6/16 Strings 8

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

Defining a String Function Start w/ string variable Holds string to work on Make it the parameter Body is all assignments Make variables as needed But last line is a return Try to work in reverse Start with the return Figure ops you need Make a variable if unsure Assign on previous line def middle(text): """Returns: middle 3 rd of text Param text: a string""" # Get length of text size = len(text) # Start of middle third start = size/3 # End of middle third end = 2*size/3 # Get the text result = text[start:end] # Return the result return result 9/6/16 Strings 10

Defining a String Function Start w/ string variable Holds string to work on Make it the parameter Body is all assignments Make variables as needed But last line is a return Try to work in reverse Start with the return Figure ops you need Make a variable if unsure Assign on previous line def middle(text): """Returns: middle 3 rd of text Param text: a string""" # Get length of text # Start of middle third # End of middle third # Get the text # Return the result return result 9/6/16 Strings 11

Defining a String Function Start w/ string variable Holds string to work on Make it the parameter Body is all assignments Make variables as needed But last line is a return Try to work in reverse Start with the return Figure ops you need Make a variable if unsure Assign on previous line def middle(text): """Returns: middle 3 rd of text Param text: a string""" # Get length of text # Start of middle third # End of middle third # Get the text result = text[start:end] # Return the result return result 9/6/16 Strings 12

Defining a String Function Start w/ string variable Holds string to work on Make it the parameter Body is all assignments Make variables as needed But last line is a return Try to work in reverse Start with the return Figure ops you need Make a variable if unsure Assign on previous line def middle(text): """Returns: middle 3 rd of text Param text: a string""" # Get length of text # Start of middle third # End of middle third end = 2*size/3 # Get the text result = text[start:end] # Return the result return result 9/6/16 Strings 13

Defining a String Function Start w/ string variable Holds string to work on Make it the parameter Body is all assignments Make variables as needed But last line is a return Try to work in reverse Start with the return Figure ops you need Make a variable if unsure Assign on previous line def middle(text): """Returns: middle 3 rd of text Param text: a string""" # Get length of text # Start of middle third start = size/3 # End of middle third end = 2*size/3 # Get the text result = text[start:end] # Return the result return result 9/6/16 Strings 14

Defining a String Function Start w/ string variable Holds string to work on Make it the parameter Body is all assignments Make variables as needed But last line is a return Try to work in reverse Start with the return Figure ops you need Make a variable if unsure Assign on previous line def middle(text): """Returns: middle 3 rd of text Param text: a string""" # Get length of text size = len(text) # Start of middle third start = size/3 # End of middle third end = 2*size/3 # Get the text result = text[start:end] # Return the result return result 9/6/16 Strings 15

Defining a String Function >>> middle('abc') 'b' >>> middle('aabbcc') 'bb' >>> middle('aaabbbccc') 'bbb' def middle(text): """Returns: middle 3 rd of text Param text: a string""" # Get length of text size = len(text) # Start of middle third start = size/3 # End of middle third end = 2*size/3 # Get the text result = text[start:end] # Return the result return result 9/6/16 Strings 16

def greet(n): Not All Functions Need a Return """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 The call frame is EMPTY 9/6/16 Strings 17

Procedures vs. Fruitful Functions Procedures Functions that do something Call them as a statement Example: greet('walker') Fruitful Functions Functions that give a value Call them in an expression Example: x = round(2.56,1) Historical Aside Historically function = fruitful function But now we use function to refer to both 9/6/16 Strings 18

Print vs. Return Print Displays a value on screen Used primarily for testing Not useful for calculations Return Defines a function s value Important for calculations But does not display anything def print_plus(n): print (n+1) >>> x = print_plus(2) 3 >>> def return_plus(n): return (n+1) >>> x = return_plus(2) >>> 9/6/16 Strings 19

Print vs. Return Print Displays a value on screen Used primarily for testing Not useful for calculations Return Defines a function s value Important for calculations But does not display anything def print_plus(n): print (n+1) >>> x = print_plus(2) def return_plus(n): return (n+1) >>> x = return_plus(2) 3 >>> x >>> x 3 Nothing here! 9/6/16 Strings 20

Advanced String Features: Method Calls Methods calls are unique (right now) to strings Like a function call with a string in front Usage: string.method(x,y ) The string is an implicit argument Example: upper() s = 'Hello World' s.upper() == 'HELLO WORLD' s[1:5].upper() == 'ELLO' 'abc'.upper() == 'ABC' Will see why we do it this way later in course 9/6/16 Strings 21

Examples of String Methods s 1.index(s 2 ) Position of the first instance of s 2 in s 1 s 1.count(s 2 ) Number of times s 2 appears inside of s 1 s.strip() A copy of s with whitespace removed at ends s = 'abracadabra' s.index('a') == 0 s.index('rac') == 2 s.count('a') == 5 s.count('b') == 2 s.count('x') == 2 ' a b '.strip() == 'a b' See Python Docs for more 9/6/16 Strings 22

String Extraction Example def firstparens(text): """Returns: substring in () Uses the first set of parens Param text: a string with ()""" # Find the open parenthesis start = s.index('(') # Store part AFTER paren tail = s[start+1:] # Find the close parenthesis end = tail.index(')') # Return the result return tail[:end] >>> s = 'Prof (Walker) White' >>> firstparens(s) 'Walker >>> t = '(A) B (C) D' >>> firstparens(t) 'A' 9/6/16 Strings 23

String Extraction Puzzle def second(thelist): """Returns: second elt in thelist The list is a sequence of words separated by commas, spaces. Ex: second('a, B, C') => 'B' Param thelist: a list of words""" >>> second('cat, dog, mouse, lion') 'dog' >>> second('apple, pear, banana') 'pear' 1 2 3 4 5 start = thelist.index(',') tail = thelist[start+1:] end = tail.index(',') result = tail[:end] return result 9/6/16 Strings 24

String Extraction Puzzle 1 2 3 4 5 def second(thelist): """Returns: second elt in thelist The list is a sequence of words separated by commas, spaces. Ex: second('a, B, C') => 'B' Param thelist: a list of words""" start = thelist.index(',') tail = thelist[start+1:] end = tail.index(',') result = tail[:end] return result >>> second('cat, dog, mouse, lion') 'dog' >>> second('apple, pear, banana') 'pear' Where is the error? A: Line 1 B: Line 2 C: Line 3 D: Line 4 E: There is no error 9/6/16 Strings 25

String Extraction Puzzle 1 2 3 4 5 def second(thelist): """Returns: second elt in thelist The list is a sequence of words separated by commas, spaces. Ex: second('a, B, C') => 'B' Param thelist: a list of words""" start = thelist.index(',') tail = thelist[start+1:] end = tail.index(',') result = tail[:end] return result >>> second('cat, dog, mouse, lion') 'dog' >>> second('apple, pear, banana') 'pear' tail = thelist[start+2:] OR result = tail[:end].strip() 9/6/16 Strings 26