Week_8_Lists_Strings

Week_8_Lists_Strings - CMPT120 J. Ye Lists and Strings (...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
CMPT120 J. Ye Lists and Strings ( Week 8 ) Sequences: Strings and Lists Sequence Indexing String Operations List Operations CMPT120 J. Ye 1 Sequences A sequence is an ordered set of values There are a number of different types of sequence: Lists Strings (sequence of characters) Tuples The values that make up the sequence are called elements Each element in a sequence has an index: The first element has index 0 The second element has index 1 2
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
CMPT120 J. Ye A string is an ordered sequence of characters E.g. “ Gone With the Wind ” is a string. It consists of 18 ordered characters We could use indexing operator [ ] to access the elements in the string E.g. if the variable s = “Gone With the Wind” then s[0] is ‘G’ , s[1] is ‘o’ , …, s[17] is ‘d’ If n is the number of characters in the string, then the (valid) index goes from 0 to n-1 . For the above example, s[18] will cause an “index out or range” error 3 Strings and String indexing Accessing Characters in a String We could use loops to access each of the characters in a string E.g. s = “immutable” for i in range(len(s)): print(s[i]) Q: What is the output? How to convert it to while loop? 4
Background image of page 2
CMPT120 J. Ye Accessing Characters in a String (cont) Exercise 1: Define a function called initials_1 that takes two names ( a first name and a last name, both are strings ) as its parameters and returns the initials of the two names E.g. initials_1(“Donald”, “Knuth”) returns “D.K.” Exercise 2: Define a function called initials_2 that takes a full name (
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 9

Week_8_Lists_Strings - CMPT120 J. Ye Lists and Strings (...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online