Chapter 10: Strings and Hashtables

Size: px
Start display at page:

Download "Chapter 10: Strings and Hashtables"

Transcription

1 Chapter 10: Strings and Hashtables This chapter describes the string and hashtable data types in detail. Strings hold text-- words and phrases-- and are used in all applications with natural language processing. Hashtables are like lists, but they allow for non-integer indexes-- you can find information using a key word instead of by number. Strings In computer science, the term character refers to a symbol that appears on the keyboard-- a letter, digit, or punctuation mark. The term string refers to sequences of characters. In most programming languages, including Python, string literals are specified within quotation marks. 'dog', 'honey I ate the kids', and '327' are examples of string literals. Quotations marks are used to distinguish such string literals from variables, as variable names are also sequences of characters In the assignment statement: animal = 'dog' animal is a variable and its value is dog. If we were tracing the program, we'd write: animal 'dog' Strings like '327' can be confusing to beginning programmers. Consider the following code: number = '327' doublenumber = 2*number print doublenumber What do you think will be printed out? If you said 654, you'd be wrong. The correct answer is '327327'. The reason is that, to the computer, '327' is not a number, it's just a sequence of characters, a '3' followed by a '2' and then a '7'. '327' is a string literal, so when you assign the variable number to it, the variable number is marked as type string. When you multiply any variable of type string, you just repeat the characters of the string n times,

2 where n is the multiplier. Thus, 2*number=2*'327'='327327' If you left off the quotes, you'd get your 654: number = 327 doublenumber = 2*number print doublenumber Python does provide the int() function for converting a string like '327' into its integer equivalent, so you can write: number = '327' doublenumber= 2*int(number) print doublenumber and get 654. Conversely, you can also convert an integer into a string using the str() function. ASCII Table A string is a sequence of characters-- symbols on the keyboard. But how does a computer store each of the characters of a string? For the string 'aaa', does it store three images that look like the letter 'a'? The answer is no. Instead, there is a mapping table, the ASCII table, that maps a number to each symbol. So the letter 'a' is represented by the number 97, 'b' is 98, and so on. The digit '0' is represented by the number 48, '1' is 49, etc. The string 'aaa' is actually stored as four numbers: As the examples shows, a 0 is stored to denote the end of the string. We call it the end-of-string character. The string 'cat' is: Early computer systems stored the number representation for each character in 8 bits, but that only allowed for 2 8 = 256 possible characters. This worked fine for the English language and Arabic character set, but was insufficient for internationalization and characters sets like those in Japan and China. Now computer systems store each character with a 16 bit

3 number in a table known as Unicode. In most programs, the fact that the letter 'a' is really stored as 97 is inconsequential. However, there are times when the ASCII mapping table is needed, such as when converting a string representation of a number to the number itself. Python provides two functions, ord(s) and chr(s), that give programmers access to the ASCII mapping table. ord returns the ascii number of a character, while chr returns the character for a given number. So ord('a') is 97, and chr(97) is 'a'. Concatenation The familiar use of the plus sign (+) is to add numbers-- everyone understands 1+1. In Python, you can also apply the plus sign to strings. Adding two strings is called concatenation and results in the two strings being joined together, e.g., the result of the expression: "abc"+"def" is a new string, "abcdef". Let's consider an example: say we have a list holding a players golf scores, and we want to display the scores in the form hole:score, hole:score, etc. So if the golfer scored a 3 on hole 1 and a 5 on hole 2, our code would build the string: hole 1:3, hole 2:5 Here's the code: golfscorelist = [3,5] # could be any list of numbers allscores="" # begin with the empty string i=0 while i<len(golfscorelist): score="hole" + str(i+1) + ":" +str(golfscorelist[i]) #build element allscores = allscores+score #concat to allscores i=i+1 if i<len(golfscorelist): allscores=allscores+"," print allscores We start by initializing the string allscores to the empty string. This is the string equivalent to the list initialization list=[]. Just as we use append to build lists, we'll use concatenation to incrementally build allscores into our final result. We iterate through the list, as usual, with a while loop. On each iteration, we build a string for that score (e.g., ''hole 1:3'). The line:

4 score="hole" + str(i+1) + ":" +str(golfscorelist[i]) does this by concatenating the string "hole" with the hold number (i+1), a colon, and the score (golfscorelist[i]). Because (i+1) and golfscorelist[i] are both integers, we use Python's str function to convert them into strings. On the second line within the while loop: allscores = allscores+score #concat to allscores we append the current score string to the allscores string using concatenation. After incrementing our hole counter i, we check if we are on the last score: i<len(golfscorelist If not, we know we have another score to come so we can add a comma to allscores. Iterating Through a String To Python, a string is a different type than a list, but in essence a string is a list of characters. And in fact, in Python you can loop through a string like you do a list. Take for instance this code to count the occurrences of the letter 'a' in a string variable word: word = "aabbbaaabb" # could be any string i=0 count=0 while i<len(word): # do something with each character if word[i]=='a': count=count+1 i=i+1 Note the use of the function len: you can use it to find the number of characters in a string, just as you can use it to find out how many elements are in a list. Note also the use of the index operator in the statement: if word[i]=='a'

5 Just as the index operator gets an element of a list, it can also get a character in a string. If word was 'cat', then word[0] would be 'c', word[1] would be 'a', and word[2] 't'. One thing you cannot do to a string, which you can do to a list, is modify an element using an index. If word is a string, the following will give you an error: word[i]='x' in this sense, strings are immutable. You can get a slice of a string. For instance, the following code gets the first two characters of a string: astring=astring[0:2] Slice can be used to get around the 'immutable' nature of strings. Consider this function to replace the ith character of a string: def replace(astring,i,replacement): return astring[0:i]+replacement+astring[i+1:len(astring)] The code grabs the slice of the string up to i, then concatenates the replacement character, then appends the last part of the original string (from i+1 to the length of the string). For the following code: word = 'cat' word2 = replace(word,1,'x') print word2 'cxt' would be printed. Note that the variable word is not modified-- it still holds the value 'cat', and the variable word2 holds 'cxt'. We could have changed the variable word by writing: word = replace(word,1,'x')

6 Python String Functions Python has many built-in functions for manipulating strings, all listed at the Python web site: The functions are object-oriented, meaning they are called in the form: somestring.function(p1,p2) where somestring is any string and p1 and p2 are the required parameters for the functions. This object-oriented way of calling a function is different from previous functions we've looked at in that the string being manipulated is considered the "object" of the function and is found to the left of a dot and the function name. We'll discuss object-oriented programming in depth in chapter 11. The string library functions perform just about any operation one could think of. One example is the split function, which splits a string into a list of subparts based on a given delimiter. For example, consider a bookmarking site that allows a user to tag articles with keywords. Some such sites allow the user to enter the tags separated by commas. So the user might tag an article about Babe Ruth with "baseball, drinkers", meaning that the article should be categorized under "baseball" and "drinkers". The split function could be used to separate the tags: userinput="baseball,drinkers" taglist= userinput.split(",") After the call to split, taglist[0] would be "baseball", and taglist[1] would be "drinkers". Other string functions include upper and lower, which return the upper and lower cases of strings, find which returns the index of the occurrence of a substring, and startswith, which returns True if a string begins with a particular substring. Hashtables A hash table consists of key-value pairs. It is like a list, but whereas a list is indexed with a number, a hash table is indexed with a string called a key. Hashtables are useful when data is best accessed using a keyword. One example is an english-to-spanish mapping:

7 engtospan = {} # initialize the hash table engtospan['hello']='hola' #map the key 'hello' to the value 'hola' engtospan['goodbye']='adios' #map the key 'goodbye' to the value 'adios' For the hashtable engtospan, the keys are English words, and they are mapped to values that are Spanish words. Each entry in the hashtable is a key-value pair: key hello goodbye value hola adios In Python, Hashtables are called Dictionaries. Hashtable Initialization Recall that lists can be initialized either with an empty list: list=[] or with some initial data: list=[3,5,9] Hashtables are initialized in a similar fashion, using {} instead of []. You can create an empty hashtable with: engtospan={} or you can create one with initial key-value pairs: engtospan={'hello':'hola','goodbye','adios','beer','cerveza'} Note that each entry in a hash-table has two parts, the key and the value, separated by a colon. So the first entry in the code above is 'hello':'hola', with 'hello' being the key, and 'hola' the value. Commas separate the entries of the table. Hashtable Modification Recall that new items can be added to a list using the function append. With hashtables, new items are added using an assignment statement and an index:

8 engtospan["horse"]="caballo" The index "horse" is the key, and the value is "caballo". If this line of code followed the three entry initialization above, the hashtable would then have four entries. Accessing Hashtable Data Recall that list data is accessed by indexing into the list with a number. One can print the third item of a list with: print list[2] Hashtables are also accessed by indexing, but instead of accessing the ith item, one accesses data using a key (string) index. So one could print the Spanish word for "goodbye" with: print engtospan("goodbye") Or one could print the Spanish equivalent to a word input by the user with: engword = raw_input('please enter an English word:') spanword = engtospan[engword] print 'The spanish eqivalent is: ',spanword Python also provides the keys() and values() functions for iterating through all the entries of a hashtable. For instance, one could print an entire hashtable with the following code: for key in engtospan.keys(): print key+":"+engtospan[key] Using Hashtables in App Engine Hashtables have many uses. For instance, you could use a hash table to store data for each user in your system, using the user's id as a key. Hashtables are also used in web programming. In the App Engine system, which we'll be studying soon, a hashtable is used to build dynamic web pages. Consider the following HTML code: <html> <body> <p> The interest is: {{interest}} </p>

9 <p> The principal after one year is: {{principal}} </p> </body> </html> The interest and principal variable defined within double-curly brackets are called template variables. The template variables are the part of the web page that shows dynamic information, in this case the results of some banking interest computations performed by the web site server. With App Engine, the web site server code is written in Python. Suppose that the user has entered the original principal and rate of a bank account into an HTML form on a different page. The App Engine controller on the server would compute the interest earned and the new principal, then stick these results into a hash table called 'template_values' class ComputeInterestHandler(webapp.RequestHandler): def get(self): principalstring=self.request.get('principal') ratestring = self.request.get('rate') interest = int(principalstring)*int(ratestring)/100 intereststring = str(interest) principalstring = str(principal+interest) template_values={'interest':intereststring,'principal':principalstring} # render the page using the template engine path = os.path.join(os.path.dirname( file ),'index.html') self.response.out.write(template.render(path,template_values)) The template_values variable is a hash table. Each key represents one of the template variables in the HTML template. Each value represents the data that should replace those template variables when the new dynamic page is sent to the browser. In this case, the server replaces the key 'interest' with the value that was computed for it (the value in the variable intereststring), and the key 'principal' with the value that was computed for it. Summary Strings and hashtables are fundamental data types used by programmers, along with lists, integers, floating point numbers, booleans. In the following chapter, will discuss classes, which allow programmers to define their own data types.

10 Problems 1. Write a function that takes a string representation of a positive whole number as a paramter and returns the number as an integer. You can assume that the parameter is a valid number, e.g., "327" and does not have any non-digits, as in: "3&27" 2. Write a modified version of problem 1 in which your function: handles negative numbers returns 0 if the given string is not a valid whole number 3.Write a Python program that uses a hash table to map US states to their capitols, e.g., 'California' would be a key, and 'Sacramento' a value. The program should initialize the hash table with three entries, add a fourth entry on the next line, then prompt the user to enter a state. The program should print the capitol of the state entered by the user.

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

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

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

Computing with Numbers

Computing with Numbers Computing with Numbers Example output: Numeric Data Types Numeric Data Types Whole numbers are represented using the integer data type (int for short).values of type int can be positive or negative whole

More information

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012 Computing with Strings CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Learning Outcomes To understand the string data type and how strings are represented

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Introduction to: Computers & Programming: Strings and Other Sequences

Introduction to: Computers & Programming: Strings and Other Sequences Introduction to: Computers & Programming: Strings and Other Sequences in Python Part I Adam Meyers New York University Outline What is a Data Structure? What is a Sequence? Sequences in Python All About

More information

Sequences: Strings, Lists, and Files

Sequences: Strings, Lists, and Files Sequences: Strings, Lists, and Files Read: Chapter 5, Sections 11.1-11.3 from Chapter 11 in the textbook Strings: So far we have examined in depth two numerical types of data: integers (int) and floating

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

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

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Strings and Escape Characters Primitive Data Types Variables, Initialization, and Assignment Constants Reading for this lecture: Dawson, Chapter 2 http://introcs.cs.princeton.edu/python/12types

More information

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

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

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

Sequence of Characters. Non-printing Characters. And Then There Is   Subset of UTF-8. String Representation 6/5/2018. Chapter 4 Working with Strings Sequence of Characters we've talked about strings being a sequence of characters. a string is indicated between ' ' or " " the exact sequence of characters is maintained

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

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

Working with Strings. Husni. The Practice of Computing Using Python, Punch & Enbody, Copyright 2013 Pearson Education, Inc. Working with Strings Husni "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc. Sequence of characters We've talked about strings being a sequence of characters.

More information

Introduction to: Computers & Programming: Strings and Other Sequences

Introduction to: Computers & Programming: Strings and Other Sequences Introduction to: Computers & Programming: Strings and Other Sequences in Python Part I Adam Meyers New York University Outline What is a Data Structure? What is a Sequence? Sequences in Python All About

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

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

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

CSC Web Programming. Introduction to JavaScript

CSC Web Programming. Introduction to JavaScript CSC 242 - Web Programming Introduction to JavaScript JavaScript JavaScript is a client-side scripting language the code is executed by the web browser JavaScript is an embedded language it relies on its

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

COMP1730/COMP6730 Programming for Scientists. Strings

COMP1730/COMP6730 Programming for Scientists. Strings COMP1730/COMP6730 Programming for Scientists Strings Lecture outline * Sequence Data Types * Character encoding & strings * Indexing & slicing * Iteration over sequences Sequences * A sequence contains

More information

MITOCW watch?v=rvrkt-jxvko

MITOCW watch?v=rvrkt-jxvko MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

3. Conditional Execution

3. Conditional Execution 3. Conditional Execution Topics: Boolean values Relational operators if statements The Boolean type Motivation Problem: Assign positive float values to variables a and b and print the values a**b and b**a.

More information

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries Assignment: Lab 12 Tuples and Dictionaries Due Date: During discussion, November 30 th through December 3 rd Value: 1% of final grade Part 1: Data Types

More information

3. Conditional Execution

3. Conditional Execution 3. Conditional Execution Topics: Boolean values Relational operators if statements The Boolean type Motivation Problem: Assign positive float values to variables a and b and print the values a**b and b**a.

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

COMS 469: Interactive Media II

COMS 469: Interactive Media II COMS 469: Interactive Media II Agenda Review Data Types & Variables Decisions, Loops, and Functions Review gunkelweb.com/coms469 Review Basic Terminology Computer Languages Interpreted vs. Compiled Client

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Unit E Step-by-Step: Programming with Python

Unit E Step-by-Step: Programming with Python Unit E Step-by-Step: Programming with Python Computer Concepts 2016 ENHANCED EDITION 1 Unit Contents Section A: Hello World! Python Style Section B: The Wacky Word Game Section C: Build Your Own Calculator

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Control structure: Repetition - Part 1

Control structure: Repetition - Part 1 Control structure: Repetition - Part 1 01204111 Computers and Programming Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org

More information

Topic 7: Lists, Dictionaries and Strings

Topic 7: Lists, Dictionaries and Strings Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Semester 2, 2018: Lab 5

Semester 2, 2018: Lab 5 Semester 2, 2018: Lab 5 S2 2018 Lab 5 Note: If you do not have time to finish all exercises (in particular, the programming problems) during the lab time, you should continue working on them later. You

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

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

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

More information

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON Table of contents 2 1. Learning Outcomes 2. Introduction 3. The first program: hello world! 4. The second program: hello (your name)! 5. More data types 6.

More information

UNIT 5. String Functions and Random Numbers

UNIT 5. String Functions and Random Numbers UNIT 5 String Functions and Random Numbers DAY 1 String data type String storage in data String indexing I can.. Explain the purpose of the string variable type and how it is stored in memory. Explain

More information

To add something to the end of a list, we can use the append function:

To add something to the end of a list, we can use the append function: 4.2 Lists Creating an Empty List A list is a sequence of items. In python, a list is an ordered sequence of items, not necessarily of the same type, but typically, most lists contain items all of the same

More information

CPS122 Lecture: From Python to Java

CPS122 Lecture: From Python to Java Objectives: CPS122 Lecture: From Python to Java last revised January 7, 2013 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

Slicing. Open pizza_slicer.py

Slicing. Open pizza_slicer.py Slicing and Tuples Slicing Open pizza_slicer.py Indexing a string is a great way of getting to a single value in a string However, what if you want to use a section of a string Like the middle name of

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation

More information

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

The second statement selects character number 1 from and assigns it to. Chapter 8 Strings 8.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: The second statement selects character number 1

More information

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018 Python Input, output and variables Lecture 23 COMPSCI111/111G SS 2018 1 Today s lecture What is Python? Displaying text on screen using print() Variables Numbers and basic arithmetic Getting input from

More information

Strings are actually 'objects' Strings

Strings are actually 'objects' Strings Strings are actually 'objects' Strings What is an object?! An object is a concept that we can encapsulate data along with the functions that might need to access or manipulate that data. What is an object?!

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All This chapter discusses class String, from the java.lang package. These classes provide the foundation for string and character manipulation

More information

Introduction to Programming, Aug-Dec 2006

Introduction to Programming, Aug-Dec 2006 Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components

More information

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans Computer Science 121 Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans 3.1 The Organization of Computer Memory Computers store information as bits : sequences of zeros and

More information

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

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Strings Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 Strings Sequence of characters

More information

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

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

CS 234 Python Review Part 2

CS 234 Python Review Part 2 CS 234 Python Review Part 2 Recap import function: define, return boolean, conditional, branching loop: for, range, while file: open, close, readlines string: split Classes Define blueprint for a custom

More information

Advanced Algorithms and Computational Models (module A)

Advanced Algorithms and Computational Models (module A) Advanced Algorithms and Computational Models (module A) Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 34 Python's built-in classes A class is immutable if each object of that class has a xed value

More information

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All Advanced Java This chapter discusses class String, class StringBuilder and class Character from the java.lang package. These classes provide

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 3: Creating and Modifying Text

Chapter 3: Creating and Modifying Text Chapter 3: Creating and Modifying Text Chapter Learning Objectives Which of the statements below is true after these two statements are executed? (Can be more than one.) 1)Variable a is now empty 2)Variable

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

3 The Building Blocks: Data Types, Literals, and Variables

3 The Building Blocks: Data Types, Literals, and Variables chapter 3 The Building Blocks: Data Types, Literals, and Variables 3.1 Data Types A program can do many things, including calculations, sorting names, preparing phone lists, displaying images, validating

More information

Iteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration?

Iteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration? Iteration Part 1 Motivation for iteration Display time until no more time left Iteration is a problemsolving strategy found in many situations. Keep coding until all test cases passed CS111 Computer Programming

More information

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0 INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0 OCTOBER 2014 Python Selection and Conditionals 1 SELECTION AND CONDITIONALS WHAT YOU MIGHT KNOW ALREADY You will probably be familiar

More information

Python - Variable Types. John R. Woodward

Python - Variable Types. John R. Woodward Python - Variable Types John R. Woodward Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

Python for ArcGIS. Lab 1.

Python for ArcGIS. Lab 1. Python for ArcGIS. Lab 1. Python is relatively new language of programming, which first implementation arrived around early nineties of the last century. It is best described as a high level and general

More information

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

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

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

Strings, Lists, and Sequences

Strings, Lists, and Sequences Strings, Lists, and Sequences It turns out that strings are really a special kind of sequence, so these operations also apply to sequences! >>> [1,2] + [3,4] [1, 2, 3, 4] >>> [1,2]*3 [1, 2, 1, 2, 1, 2]

More information

Lecture 3. Input, Output and Data Types

Lecture 3. Input, Output and Data Types Lecture 3 Input, Output and Data Types Goals for today Variable Types Integers, Floating-Point, Strings, Booleans Conversion between types Operations on types Input/Output Some ways of getting input, and

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

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

For strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table. 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,

More information

CSCA20 Worksheet Strings

CSCA20 Worksheet Strings 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

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 09 Strings Last Class We Covered Lists and what they are used for Getting the length of a list Operations like append() and remove() Iterating over a list

More information

Python for Everybody. Exploring Data Using Python 3. Charles R. Severance

Python for Everybody. Exploring Data Using Python 3. Charles R. Severance Python for Everybody Exploring Data Using Python 3 Charles R. Severance 8.14. DEBUGGING 103 In this example you could also use the built-in function sorted, which returns a new, sorted list and leaves

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

Introduction to String Manipulation

Introduction to String Manipulation Introduction to Computer Programming Introduction to String Manipulation CSCI-UA.0002 What is a String? A String is a data type in the Python programming language A String can be described as a "sequence

More information

Basic data types. Building blocks of computation

Basic data types. Building blocks of computation Basic data types Building blocks of computation Goals By the end of this lesson you will be able to: Understand the commonly used basic data types of C++ including Characters Integers Floating-point values

More information

Key Differences Between Python and Java

Key Differences Between Python and Java Python Python supports many (but not all) aspects of object-oriented programming; but it is possible to write a Python program without making any use of OO concepts. Python is designed to be used interpretively.

More information

6. Data Types and Dynamic Typing (Cont.)

6. Data Types and Dynamic Typing (Cont.) 6. Data Types and Dynamic Typing (Cont.) 6.5 Strings Strings can be delimited by a pair of single quotes ('...'), double quotes ("..."), triple single quotes ('''...'''), or triple double quotes ("""...""").

More information

Notebook. March 30, 2019

Notebook. March 30, 2019 Notebook March 30, 2019 1 Complex Data Types Some kinds of data can store other kinds of data. 1.1 Lists We ve actually seen the most common complex data type a few times before, I just haven t pointed

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

String Processing CS 1111 Introduction to Programming Fall 2018

String Processing CS 1111 Introduction to Programming Fall 2018 String Processing CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 10] 1 Collections Ordered, Dup allow List Range String Tuple Unordered, No Dup Dict collection[index] Access an

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #29 Arrays in C (Refer Slide Time: 00:08) This session will learn about arrays in C. Now, what is the word array

More information

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

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT Python The way of a program Srinidhi H Asst Professor Dept of CSE, MSRIT 1 Problem Solving Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 12 Tuples All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Modularity Meaning Benefits Program design Last Class We Covered Top

More information

JavaScript Basics. The Big Picture

JavaScript Basics. The Big Picture JavaScript Basics At this point, you should have reached a certain comfort level with typing and running JavaScript code assuming, of course, that someone has already written it for you This handout aims

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

UNIVERSITÀ DI PADOVA. < 2014 March >

UNIVERSITÀ DI PADOVA. < 2014 March > UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

Python Input, output and variables

Python Input, output and variables Today s lecture Python Input, output and variables Lecture 22 COMPSCI111/111G SS 2016! What is Python?! Displaying text on screen using print()! Variables! Numbers and basic arithmetic! Getting input from

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

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

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 09 Strings Last Class We Covered Lists and what they are used for Getting the length of a list Operations like append() and remove() Iterating over a list

More information

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016 Python Input, output and variables Lecture 22 COMPSCI111/111G SS 2016 Today s lecture u What is Python? u Displaying text on screen using print() u Variables u Numbers and basic arithmetic u Getting input

More information