6 Strings and Tuples © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.

Slides:



Advertisements
Similar presentations
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Advertisements

CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
9 Dictionaries © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
Writing Solid Code Introduction to Python. Program 1 python -c "print 'Hello World' “ python -c "import time; print time.asctime()“ Start an interactive.
The Data Element. 2 Data type: A description of the set of values and the basic set of operations that can be applied to values of the type. Strong typing:
Guide to Programming with Python
The Data Element. 2 Data type: A description of the set of values and the basic set of operations that can be applied to values of the type. Strong typing:
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 8 More on Strings and Special Methods 1.
Python Programming Chapter 7: Strings Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
I Power Int 2 Computing Software Development High Level Language Constructs.
Data Structures and Algorithms -- Chapter 3 Abstract Data Types Mohamed Mustaq.
8 For-Statements © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
Built-in Data Structures in Python An Introduction.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Chapter 5 Strings CSC1310 Fall Strings Stringordered storesrepresents String is an ordered collection of characters that stores and represents text-based.
I Power Higher Computing Software Development High Level Language Constructs.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 8: Fun with strings.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
More Strings CS303E: Elements of Computers and Programming.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Mr. Fowler Computer Science 14 Feb 2011 Strings in Python.
Strings The Basics. Strings a collection data type can refer to a string variable as one variable or as many different components (characters) string.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
3 Basics © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
12 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings … operators Up to now, strings were limited to input and output and rarely used as a variable. A string is a sequence of characters or a sequence.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
Computer Science 18 Feb 2011 Strings in Python. Introduction Prior experience  Defining string variables  Getting user input  Printing strings Lesson.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
Unit 4 – Chapter 4 Strings and Tuples. len() Function You can pass any sequence you want to the len() function and it will return the length of the sequence.
 Type Called bool  Bool has only two possible values: True and False.
String and Lists Dr. José M. Reyes Álamo.
Tuples and Lists.
CHAPTER 7 STRINGS.
Introduction to Programming
Chapter 8 More on Strings and Special Methods
CEV208 Computer Programming
String and Lists Dr. José M. Reyes Álamo.
Basic String Operations
The Data Element.
Topics Basic String Operations String Slicing
Introduction to Computer Science
Introduction to Programming
Topics Basic String Operations String Slicing
The Data Element.
By Himanshi dixit 11th ’B’
CS 100: Roadmap to Computing
Topics Basic String Operations String Slicing
COMPUTING.
Presentation transcript:

6 Strings and Tuples © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1

6-2 Strings revisited  Recall that a string is a sequence of characters, possibly empty.  Recall string operators, e.g.: s + t concatenation of strings s and t n * s concatenation of n copies of s  Recall string comparison operators, e.g.: s == t True iff s is equal to t s < t True iff s is lexicographically less than t s > t True iff s is lexicographically greater than t

6-3 String literals  Three forms: 'qwerty' – a single-quoted string "qwerty" – a double-quoted string '''qwertyuiop asdfghjkl zxcvbnm''' – a triple-quoted multi-line string

6-4 Built-in string function  String function: len( s ) returns the length of string s

6-5 String positions  The positions within a string of length n are numbered 0, 1,..., n, e.g.: s= 'QWERTY' results in s Q W E RTY

6-6 String indexing  The expression s[i] indexes the string s to yield the single character at position i. –If i is non-negative, yield the character just to the right of position i. E.g.: s[0] yields 'Q' s[5] yields 'Y' –If i is negative, count backward from the end of the string, yielding the character just to the right of position len(s)+i. E.g.: s[-1] yields 'Y' s[-3] yields 'R' –1–2–3–4–5– s Q W E RTY

6-7 String slicing (1)  The expression s[i:j] slices the string s to yield a substring, consisting of the characters between positions i and j in s. –If i (or j ) is non-negative, count forward from the start of the string, as above. –If i (or j ) is negative, count backward from the end of the string, as above. s[0:2] yields 'QW' s[2:-1] yields 'ERTY' s[1:4] yields 'WER' s[3:3] yields '' –1–2–3–4–5– s Q W E RTY

6-8 String slicing (2)  The expression s[i:j] can be simplified if we want a leftmost or rightmost substring. –If i is omitted, the default position is 0. –If j is omitted, the default position is len(s). s[:2] yields 'QW' s[2:] yields 'ERTY' s[:3] yields 'QWE' s[:] yields 'QWERTY' –1–2–3–4–5– s Q W E RTY

6-9 String immutability  Strings are immutable – we cannot change the characters within an existing string. E.g.: s[1] = 'U' fails  To achieve the desired effect, we must construct a new string: t = s[0] + 'U' + s[2:] s Q W E RTY t Q U E RTY  Of course, a newly constructed string can be shorter or longer than the original string.

6-10 Testing substrings  Another string comparison operator: s 1 in s 2 True iff s 1 is a substring of s 2  E.g.: 'QW' in s yields True 'QU' in s yields False 'ERT' in s yields True s in s yields True t in s yields False

6-11 Example: string processing (1)  Many Internet domain names end with a 2-letter country code (e.g., ‘gr’, ‘lt’, ‘pl’, or ‘uk’).  Function on domain names: def country (dn): # Return the 2-letter country code in domain # name dn, or ‘’ if there is no country code. if len(dn) > 3 \ and dn[-3] = '.' \ and alphabetic(dn[-2]) \ and alphabetic(dn[-1]): return dn[-2:] else: return ''

6-12 Example: string processing (2)  Auxiliary function and constant: def alphabetic (ch): # Return True iff ch is a letter. return (ch in letters) letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz'  Function calls: country(' yields ‘uk’ country(' yields ‘uk’ country(' yields ‘’

6-13 Formatting strings (1)  String formatting operator: s % x yields a string in which a representation of value x is embedded in string s s % ( x 1, …, x n ) yields a string in which representations of values x 1, …, x n are embedded in string s  E.g., if m contains 1234, t contains 70.4, fn contains ‘James’, and sn contains ‘Bond’: 'Balance is £%d.' % m yields ‘Balance is £1234.’ 'Distance is %f km.' % d yields ‘Distance is 70.4 km.’ 'My name is %s %s.' % (fn, sn) yields ‘My name is James Bond.’

6-14 Formatting strings (2)  In “s % x”, string s must contain a format- specification consistent with the type of value x: –%d specifies where an integer literal will be embedded. –%f specifies where a floating-point literal will be embedded. –%s specifies where a string will be embedded.  In “s % ( x 1, …, x n ) ”, string s must contain n format-specifications consistent with the types of values x 1, …, x n.

6-15 Example: string formatting (1)  Template for a form letter: template = '''%s %s %s\n\ %s Dear %s %s, Thanks for your enquiry. We will send you an application pack within %d working days. Yours sincerely, Student Admissions Officer University of Poppleton'''

6-16 Example: string formatting (2)  Function to print a form letter: def print_letter \ (title, forename, surname, address): # Print a form letter addressed to the named person. print template % \ (title, forename, surname, \ address, title, surname, 3)

6-17 Example: string formatting (3)  Function call: print_letter( ' Mr ', ' Joe ', ' Bloggs ', \ ' Skid Row, Grimethorpe ' )  Output: Mr Joe Bloggs Skid Row, Grimethorpe Dear Mr Bloggs, Thanks for your enquiry. We will send you an application pack within 3 working days. Yours sincerely, Student Admissions Officer University of Poppleton

6-18 Tuples  A tuple is an immutable group of values. These values are called the components (or fields) of the tuple.  Constructing a tuple: name = ('James', 'Bond') constructs a pair (2 components) today = (1, 'Oct', 2010) constructs a triple (3 components)

6-19 Accessing tuple components (1)  The components of an n-tuple are numbered 0, 1, …, n–1.  The expression “t [ i ] ” yields component i of tuple t. E.g.: name[0] yields ‘James’ name[1] yields ‘Bond’ today[0] yields 1 today[1] yields ‘Oct’ today[2] yields 2010

6-20 Accessing tuple components (2)  The statement “v 1, …, v n = t ” assigns the components of tuple t to variables v 1, …, v n, respectively. (This works only if t has exactly n components.) E.g.: fn, sn = name stores ‘James’ in fn, ‘Bond’ in sn d, m, y = today stores 1 in d, ‘Oct’ in m, 2010 in y

6-21 Example: dates (1)  We can represent a date by a triple of integers (day number, month number, year number).  Some functions on dates: def year (date): # Return the year number of date. return date[2] def anniversary (date): # Return the anniversary of date, i.e., # the same date 1 year later. d, m, y = date return (d, m, y+1)

6-22 Example: dates (2)  Functions on dates (continued): def next (date): # Return the next day after date. d, m, y = date if d < length(m, y): return (d+1, m, y) elif m < 12: return (1, m+1, y) else: return (1, 1, y+1) def length (m, y): # Return the number of days in month m of year y. …