For strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table.

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

Program Planning, Data Comparisons, Strings

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

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

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

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

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Data Structures. Lists, Tuples, Sets, Dictionaries

Python Review IPRE

CPD for GCSE Computing: Practical Sheet 6 February 14

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

TUPLES AND RECURSIVE LISTS 5

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

IT441. Network Services Administration. Data Structures: Lists

MITOCW watch?v=rvrkt-jxvko

Collections. Lists, Tuples, Sets, Dictionaries

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

Slicing. Open pizza_slicer.py

The Dynamic Typing Interlude

ENGR 102 Engineering Lab I - Computation

Lists, loops and decisions

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Play with Python: An intro to Data Science

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Overview of List Syntax

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

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

6. Data Types and Dynamic Typing (Cont.)

Python - Variable Types. John R. Woodward

Python for C programmers

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

Python Review IPRE

Full file at

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

MITOCW watch?v=kz7jjltq9r4

Fundamentals of Python: First Programs. Chapter 4: Strings and Text Files

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

UNIVERSITÀ DI PADOVA. < 2014 March >

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

The Practice of Computing Using PYTHON

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

printf( Please enter another number: ); scanf( %d, &num2);

Topic 7: Lists, Dictionaries and Strings

Maple for Math Majors. 12. Data Structures in Maple

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

"Hello" " This " + "is String " + "concatenation"

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

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

COMP1730/COMP6730 Programming for Scientists. Strings

Here is a simple dictionary in Python. Let s store the telephone dialing codes for a few countries.

Some material adapted from Upenn cmpe391 slides and other sources

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

The second statement selects character number 1 from and assigns it to.

CS 11 Haskell track: lecture 1

Chapter 2. Editing And Compiling

String Processing CS 1111 Introduction to Programming Fall 2018

Introduction to Python

Advanced Algorithms and Computational Models (module A)

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Spring Semester 11 Exam #1 Dr. Dillon. (02/15)

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

ENGR 102 Engineering Lab I - Computation

Introduction to String Manipulation

IAP Python - Lecture 2

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

6.001 Notes: Section 6.1

6.001 Notes: Section 15.1

Compound Data Types 1

Types, lists & functions

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

The Big Python Guide

Python Intro GIS Week 1. Jake K. Carr

JME Language Reference Manual

MUTABLE LISTS AND DICTIONARIES 4

Introduction to Python - Part I CNV Lab

Programming in C++ PART 2

Programming Fundamentals and Python

Intro. Classes & Inheritance

Chapter 2: Lists, Arrays and Dictionaries

Introduction to Python

ENGR 101 Engineering Design Workshop

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

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

Program Syntax; Operational Semantics

COLLEGE OF ENGINEERING, NASHIK-4

Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th.

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

6.001 Notes: Section 1.1

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Programming in Python

Key Differences Between Python and Java

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

Most of the class will focus on if/else statements and the logical statements ("conditionals") that are used to build them. Then I'll go over a few

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

Chapter 10: Strings and Hashtables

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1

Transcription:

Page 1 6.189 Notes Session 8 Day 6: Immutable Objects Earlier, we made a big deal about the fact that lists are mutable. The reason this is important is because certain objects are immutable once created, their value cannot be changed. Strings are a prime example of this. Although we treated strings the same as primitives like integers and booleans earlier, strings are actually objects. Why did we do this? Think about this: if an object is immutable, it doesn't matter whether two variables are pointing to the same string or two different strings with the same value! Thus, while strings are actually immutable objects, we can treat them as we have before as primitives. The only new meaning this revelation has is that like lists, strings have member functions. For strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table. Day 6: Strings Revisited Most of the member functions in lists modified the list and had no return value. Strings are immutable, though how do string member functions work? It turns out that member functions of strings tend to return a new string. Program Text: message = "Hello" message.lower() #no effect message = message.lower() Output: Hello Hello hello Note: lower()is a function that converts a string into lowercase. Here is a list of some useful string functions. Don't try to memorize these! Even I don't remember them instead, when I need to look up a function I go to the Python Quick Reference website shown in class (and on the website.)

Page 2 A quick reminder before starting: remember that "A" and "a" are completely different characters! When writing functions that manipulate strings, its generally a good idea to deal with a single case (usually lowercase). Functions that return a new string str.capitalize() / str.lower(). Returns a copy of str with all letters converted to uppercase / lowercase. str.strip(). Returns a copy of str with all whitespace (spaces/tabs/newlines) from the beginning and end of the string removed. Example: " test ".strip() == "test". str.replace(old,new). Returns a copy of str with all instances of old within the string replaced with new. Example: "hallo all!".replace("al", "el") == "hello ell!". Functions which return information about a string str.count(substring).returns the number of times substringappears within str. str.find(substring) / str.rfind(substring). Returns the position of the first instance of substringwithin str. rfind returns the position of the last instance of substring. s.startswith(substring) / str.endswith(substring). Returns True if the string starts with / ends with substring. Example: "Hello".startswith( he ) == False, but Hello.endswith( lo ) == True Functions which transform the string into other types str.split(separator). Returns a list of words in str, using separator as the delimiter string. Example: "hello world, Mihir here".split(" ")returns ["hello","world,","mihir","here"]. Example: "mississippi".split("s")returns ["mi", "", "i", "", "ippi"]. separator.join(seq). This one is tricky. It takes a list of strings seq and combines them into a string. Each element in seqis separated by separatorin the returned string. Example: " ".join(["hello","world"]) == "hello world" Day 4: Tuples Tuples are the immutable counterpart of lists. Unlike a list, tuples cannot be changed. Why/where are tuples useful? Think of a tuple as multi-dimensional data -- just like you can store an integer 5 in a variable, you can also store a two-dimensional coordinate (6,-3). You'll develop an instinct for when to use tuples versus lists as you continue in course 6 just remember that it tends to be much easier to use tuples whenever you can get away with it. You can create tuples by using parentheses: (1,3,8) creates the tuple with elements 1, 3, 8. As you should expect, tuples are ordered: (1,3)!= (3,1)

Page 3 If you want to create a singleton tuple (a tuple with one element), you can use tuple(5) or use the notation (5,). Note that (5,)!= 5 they have completely different types (the former is a tuple and the latter is an integer. Also note that (4,6)!= [4,6] one is a tuple and the other is a list. Similarly, ("a","b")!= "ab". You can convert between these three formats using str(x), tuple(x), and list(x), though. You can nest tuples in tuples! Note that ((1,2),3)!= (1,2,3) the former is a tuple that contains two elements (one tuple and one integer), whereas the latter is a tuple that contains three elements. Notation for using tuples will be covered in the next section. Day?: Sequence notation Lists, strings and tuples are all examples of sequences a series of ordered items. In the case of strings, you can think of them as a sequence of characters. Sequence isn't an official term or anything just an observation that all three of these are very similar. In fact, they share much of the same syntax. Indexing. seq[i] will return the item (or character) at the ith position. Length. len(seq) returns the length of a sequence. Slicing. You can slice sequences the same way you sliced lists. "hello"[0:3] == "hel" in, not inoperators. x in seqis Trueif and only if an item of seqis equal to x. For strings, you can check if a substring is in a string, e.g. "ello" in "hello"returns True. Concatenation. You can use the plus operator to combine two sequences of the same type. You can use *to duplicate it ntimes for some integer n, e.g. "Yay! " * 5 For loops. We learned that the foroperator works on lists. foractually works onany sequence for strings, it iterates through each character in the string. Day 7: Dictionaries And so we come to the last major topic of this class: dictionaries. Like lists, dictionaries are an mutable object that we can use to store data. Where lists stored a sequence of items, dictionaries store a table.

Page 4 Note that dictionaries are considered to be unordered it doesn't matter what order we list entries in. We call the names on the left keys and the values on the right values. You can store primitives and immutable objects (like strings and tuples) as keys. You can store anything (e.g. lists) as a value. As we go through the dictionary notation, notice that a lot of it is consistent with the sequence notation above the notation below should seem intuitive to you. Remember that dictionaries are fundamentally different from sequences, though especially the fact that dictionaries are unordered. You can create a new dictionary using curly braces. Example: example_dict = {}creates an empty dictionary Example: example_dict = {"a":5, "test":[1,2], 27:"Test"}creates the above table. The amount of spacing around the colon :is irrelevant. len(d)works on dictionaries too -use it to find the number of entries in the dictionary (the above dictionary has length 3.) To access or change a value, use the same index notation. Example: print example_dict["a"] prints 5 Example: example_dict["a"] = 7 Note that this implies that a dictionary cannot contain two identical keys writing example_dict["a"] = 7 would just change the value that a is mapped to. This should make sense, though remember that dictionaries are unordered. Also, you can have a dictionary with identical values. Use del example_dict["a"]to remove that entry from the dictionary. k in d will return true if the dictionary d contains an entry with key k. Example: (27 in example_dict) == True Example: (5 in example_dict) == False Day 7: Dictionary Member functions Like other objects, dictionaries have member functions. You don't really need to use these much, though here are a few that might be useful d.clear(). Removes all items from d. d.copy(). Returns a copy of the dictionary d. d.pop(k). Removes the entry with key k and returns its corresponding value. This is just like del d[k], except that the function also returns the value of d[k]. Day 7: For loops and dictionaries Remember how k in dwill return Trueif kis mapped to something? You can also use forloops with dictionaries. For loops will iterate over all the keys in the dictionary:

Page 5 Program Text: example_dict = {"a" : 5, "b" : True} for k in example_dict: print k, ";", example_dict[k] Output: a ; 5 b ; True