CSCA20 Worksheet Strings

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Strings. CSE 231 Rich Enbody. String: a sequence of characters. Indicated with quotes: or " " 9/11/13

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Python Day 3 11/28/16

Lecture 3. Input, Output and Data Types

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

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

Lecture 3. Strings, Functions, & Modules

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

At full speed with Python

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

University of Texas at Arlington, TX, USA

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

Introduction to: Computers & Programming: Review prior to 1 st Midterm

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

CMPT 125: Lecture 3 Data and Expressions

Student Number: Instructor: Brian Harrington

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

Strings and Testing string methods, formatting testing approaches CS GMU

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

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

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

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

Introduction to Python

CSC 108H: Introduction to Computer Programming. Summer Marek Janicki

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

CS 102 Lab 3 Fall 2012

Introduction to Computer Programming for Non-Majors

Overview of List Syntax

Lists How lists are like strings

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Lecture 3. Functions & Modules

Intro. Scheme Basics. scm> 5 5. scm>

UNIT 5. String Functions and Random Numbers

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

LOOPS. Repetition using the while statement

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

Python Programming: Lecture 2 Data Types

CSCI 121: Anatomy of a Python Script

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

'...' "..." escaping \u hhhh hhhh '''...''' """...""" raw string Example: r"abc\txyz\n" in code;

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

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

[301] Strings. Tyler Caraza-Harter

Announcements For This Lecture

Object Oriented Programming #10

CMSC 201 Spring 2018

AP Computer Science A

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Script language: Python Data structures

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

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

Have the students look at the editor on their computers. Refer to overhead projector as necessary.

CSC 120 Computer Science for the Sciences. Week 1 Lecture 2. UofT St. George January 11, 2016

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

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

COMP1730/COMP6730 Programming for Scientists. Strings

Babu Madhav Institute of Information Technology, UTU 2015

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Python Class-Lesson1 Instructor: Yao

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list.

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

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

Programming Fundamentals and Python

Lecture 3. Functions & Modules

Chapter 10: Creating and Modifying Text Lists Modules

ENGR 101 Engineering Design Workshop

Introduction to Python (All the Basic Stuff)

Question 1. Part (a) Simple Syntax [1 mark] Circle add_ints(), because it is missing arguments to the function call. Part (b) Simple Syntax [1 mark]

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016

More about Binary 9/6/2016

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Module 3: New types of data

Visual C# Instructor s Manual Table of Contents

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Python and Programming. 1. Python is Like a Calculator. You Type Expressions. Python Computes Their Values /2 2**3 3*4+5*6

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Introduction to Python Code Quality

BASIC ELEMENTS OF A COMPUTER PROGRAM

1 Strings (Review) CS151: Problem Solving and Programming

Advanced Python. Executive Summary, Session 1

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Programming with Python

Full file at

Chapter 9: Dealing with Errors

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

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

ENGR 102 Engineering Lab I - Computation

Announcements For This Lecture

Fundamental of Programming (C)

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Transcription:

1 Introduction to strings CSCA20 Worksheet Strings A string is just a sequence of characters. Why do you think it is called string? List some real life applications that use strings: 2 Basics We define strings using either single or double quotes csca20 or "csca20" unless it needs to span more than one line and then we use triple quotes: >>> This is a sentence... on several lines... it is too long... to fit on one line. This is a sentence\non several lines\nit is too long\nto fit on one line. Hold on, we ll find out what \n stands for shortly! Q. What do you think the result of csca + 20 is? Q. What other use does + have? We say that + is overloaded. Q. How do you think Python knows what to do? Q. Why would "csca" + 20 result in an error? Need to use conversion: >>> dept = csc >>> level = a >>> num = 20 >>> dept + level + str(num) csca20 >>> 1

Q. What do you think "ho" * 3 will do? Q. How about len("saravanapavananthan") and "ou" in "colour"? 3 Slicing Strings Since strings are sequences of characters, we sometimes want to be able to retrieve portions of the string. To do so, we need to have a way to refer the i th character. By convention, the first character has position or index 0. Each subsequent character has index one greater. Here are the ways we can access characters in a string s: s = "sliceofspam" s[0] # Grab a single character. First index is zero. s[3] s[-2] # Negative indexes are for counting from the RHS s[2:5] # Slice a string. From position 2 (inclusive) to 5 (not inclusive) s[3:] # If omit the second index, goes to the far RHS s[:8] # If omit the first index, goes from the far LHS s[:] # If omit both, goes from both extremes. # I.e., you get a copy of the whole string. s[3:-2] # You can use negative indices when slicing too. s[-5:] # s[5:2] # Nothing there! 4 String Methods We have been using some string operators such as: csc + 108 # concatenation ho * 3 # repetition ou in colour # substring There are many string methods. These particular methods belong to the str type. We call methods using the same notation as calling a function in a module: u of toronto.capitalize() campus = utsc campus.capitalize() Some methods require parameters, such as 2

campus.startswith( ut ) You need to know when you are calling a method vs calling a function; the notation is different. For example: s = "Hi, CSCA20 students!" len(s) # len is a built-in function. s is the argument passed in. s.len() # Doesn t work. len is not a string method. s.lower() # lower is a str method lower(s) # Doesn t work. lower() must be called on an object Q. How can we get a list of all string methods with their descriptions? For the methods listed below, assume that the string we are using is: s = "This is CSC120/A20". Method Output Explanation s.lower() s.replace("20", "48") s.count("i") "yabababa daba do!".count("abab") s.find("is") s.rfind("is") s.find("is", 3) s.find("is", 2) s.find("the") Define a new s = " A quite open line ". Method Output Explanation s.lstrip() s.rstrip() s.strip() 3

5 Loops Sometimes we need to do something with each character in a string. This is called looping or iterating over the string. The form for looping through a string: for char in s: <do something involving char> for, in are Python keywords char is a variable that holds the value of the current character s is the string (for now) For example, def print_vertical(s): for char in s: print(char) Q. Trace the call print vertical("word") Q. How many times does the loop execute? Sometimes we want to iterate over the indices of a string. Here is how we can reimplement print vertical (much more on this later). Recall that len(s) returns the length of the string s. def print_vertical(s): for index in range(len(s)): print(s[index]) 6 Let s Practice Let us design and implement some functions that involve strings. Count the number of occurrences of a character in a string. Count the number of vowels in a string. Reverse a string. Remove spaces from a string. Count the number of characters two strings have in common. 4

7 Escape Sequences Q. How can we put a new line or quote inside a string? We use special escape sequences. For each of the following escape sequences, guess what they do: \n \ \" \t \\ How about this example: >>> print("\\t stands for \ tab\ and is printed \ \t\ (without quotes)") \t stands for tab and is printed (without quotes) 8 Printing strings: conversion specifiers Consider this code snippet: a1 = 89 a2 = 76 a3 = 91 print("the maximum of the three grades (", a1, ",", a2, "and", a3, ") is", max(a1, a2, a3)) The result is: The maximum of the three grades ( 89, 76 and 91 ) is 91 It is a bit of a pain to intersperse variable values with non-variable text in a print statement. We can try to use +: print("the maximum of the three grades (" + a1 + "," + a2 + " and " + a3 + ") is " + max(a1, a2, a3)) Q. Why does this cause an error? Q. How can we fix it? A MUCH better fix: print("the maximum of the three grades (%d, %d and %d) is %d" % (a1, a2, a3, max(a1, a2, a3))) There is a % operator with two operands: a string on the left and a bunch of things on the right. 5

Each %d is a placeholder for a decimal (that is, base 10) integer. After the string (with its placeholders in it), you type % followed by parenthesis containing the list of values to be substituted wherever there is a %d. We call the placeholders conversion specifiers. They indicate the format (e.g., integer, float, string) we want the values printed in. Q. The % is overloaded. What else is % used for? Q. What are the other two overloaded operators we have seen? Common conversion specifiers are: %d display the object as a decimal integer %f floating point; display it with 6 decimal places by default %.2f floating point; display it with 2 decimal places (you can specify a number other than 2) %s display the object as a string Example import math print("pi is %.15f" % (math.pi)) r = 9.625 Write a print statement that calculates the area of a circle of radius r and outputs: A circle of radius 9.625000 has area 291.0391. Example Write a snippet of code to ask for the user s name and age and then print: NAME is YYY years old. 8.1 The format built-in function You may find formatting with the % operator awkward, though it does improve with familiarity. An alternative is the built-in function format, which we will not cover here. 6