This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Module 7 Strings and lists and structures More about programming in Python CS 116: Introduction to Computer Science 2 Daniel G. Brown/Troy Vasiga, University of Waterloo 7.1 Purpose of Module 7 Strings and their methods in Python Lists and their uses in Python Mutating lists Functional programming in Python Readings: PfSD 8, 10 7.2 1 Strings in Python Strings in Python Strings in Python are a basic type, just like in Scheme. We can do some things with them that we couldnt do in Scheme: >> X = desire >> print X * 3 desiredesiredesire >> Y = " for love" >> X + Y desire for love 7.3 Strings, continued Again, there are a lot of ways to write down strings in Python: You can surround the string with single quotes or double quotes. These do the same thing. Also, note the difference that if we use print , the outcome is slightly different: >> print X + Y desire for love Thats because when you just type X + Y , the interpreter shows the value of that computation, which is the string "desire for love" . What is shown when you execute print X + Y is not the value of the computation: there is no return value from print . 7.4 1 Not all arithmetic operations make sense on strings We cant multiply strings, any more than we could in Scheme: ( define z "me!" ) ( * z z ) * : expects type <number> as 1st argument, given: "me!"; other arguments were: "me!" >> z = "me!" >> z * z TypeError: cant multiply sequence by non-int of type str The problem is explained in the error: We would have needed the second argument to be a number, not a string. 7.5 Thats actually kind of strange What we just saw is actually a little strange: You could think of multiplication of strings as natural. But really, this is just a use of the * symbol to do something pretty different. When strings are defined, in effect, a new operation also got created, with the new (additional) contract: * : str int str Making new uses for basic operators is called operator overloading . Its very commonly used in object-oriented programming. Python does allow it (and well see more examples). Courses like CS 241, 246 and 432 talk about how to design code that effectively uses this feature. 7.6 Other string operations Strings have other properties we can test, like substrings: >> "astro" in "catastrophe" True >> "car" in "aluminum" False 7.7 Substrings We can also identify individual characters or substrings of a string. This gets extremely awkward, and many languages do this differently: When learning a new language, this is one of the easiest characteristics to get wrong! In Python, the basic expression is >> s = "abcde" >> print s [2:4] cd In Python, if we have the expression X [ i : j ] : The string starts with character #0, going left-to-right....
View Full Document
- Winter '09
- Computer Science