Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "6 Strings and Tuples © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1."— Presentation transcript:

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

2 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

3 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

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

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

6 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–6 1 2 3 4 560 s Q W E RTY

7 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–6 1 2 3 4 560 s Q W E RTY

8 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–6 1 2 3 4 560 s Q W E RTY

9 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:] 1 2 3 4 560 s Q W E RTY 1 2 3 4 560 t Q U E RTY  Of course, a newly constructed string can be shorter or longer than the original string.

10 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

11 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 ''

12 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('www.gla.ac.uk') yields ‘uk’ country('www.amazon.co.uk') yields ‘uk’ country('www.amazon.com') yields ‘’

13 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.’

14 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.

15 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'''

16 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)

17 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

18 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)

19 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

20 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

21 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)

22 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. …


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

Similar presentations


Ads by Google