strings and lists as objects

Sample code
In the code you copied over from my public/cs21/w06-while subdirectory are two files, stringOps.py, listOps.py, that contain example code of using strings as objects and lists as objects.

Strings as objects
Strings are a special type of a python class. As objects, in a class, you can call methods on string objects using the .methodName() notation. The string class is available by default in python, so you do not need an import statement to use the object interface to strings.

To see the list of methods call help(str) in the python interpreter:
$ python
>>> help(str)
For now, ignore methods with names that begin with __. If you want to know the full gory details, see the Technical Discussion at the end of this document. There are a lot of additional string methods not beginning with __ that you can now use. The example program, stringOps.py, has some things you can try out. Let me know if you have any questions about what it is doing:
"""
 A program showing some string operations using the dot notation
 Author: Andrew Danner
 Date: October 2008
"""

def main():
  """
   many of these one-liners can be typed directly into 
   the python shell for more practice.
  """

  s="hello"
  print "s = ",s
  print "s.upper() = ",  s.upper()
  print "s.isalpha() = ",  s.isalpha()
  print

  numStr="1992" # Last Pittsburgh Pirate winning season
  print "numStr = ",  numStr
  print "numStr.isalpha() = ", numStr.isalpha()
  print "numStr.isdigit() = ", numStr.isdigit()

  print
  sentence="Check it out!"
  print "\n\nsentence = ", sentence
  print "sentence.isalpha() = ",  sentence.isalpha()
  words = sentence.split()
  print "sentence.split() = ", words

  print
  # use join to undo a split
  # syntax is: <string>.join(<list of strings>)
  # semantics: join all elements in <list of strings> together with
  #  <string> in between each element
  separator=''
  s2 = separator.join(ls) # convert from list of characters to string 
  print "s2 = ",s2
  
main()


Lists as objects
Lists are objects too. An important method for lists is append(item). Look at the sample code in listOps.py to see how append works. Note that it modifies the existing list. It does not create a new list.

Another new syntactic feature is the if <item> in <list>:. This statement evaluates to True and executes the body of the if statement if the specified item is present one or more times in the given list.

List elements can be modified. The syntax l[0]=x changes the contents of the first item in the list l to now contain the element x. Even though strings support index and slicing syntax (e.g., s[0], s[1:3], strings cannot be modified in this way. You can however convert a string to a list of characters, modify the list and then convert the list back to a string. The end of the program shows an example of this. Could this be how the method s.replace(old, new) works in the string class?

For more on list methods, type help(list) in a python shell. Again, ignore methods that begin with the __ prefix which are invoked using using an alternate syntax. In listOps.py are some examples of list methods. We will talk about some of these methods later in the course as we need them.

listOps.py:

"""
 A program showing some list operations using the dot notation
 Author: Andrew Danner
 Date: October 2008
"""

def main():
  """
     many of these one-liners can be typed directly into 
     the python shell for more practice. look at 
     help(list) for more python list operations
  """

  l=[1,5,4]
  print "l = ",l
  l.append(6) # append modifies l. Returns nothing
  print "l after l.append(6) = ", l
  l.append(8)
  print "l after l.append(8) = ", l

  if 6 in l:
    print "yes, 6 is in l"

  s="hello"
  ls=list(s) # create a list of characters from s
  print "s=",s," ls = ", ls

  #s[0]='j' # illegal, strings cannot be modified in place
  ls[0]='j' # ok, lists can be modified
  print "modified ls = ", ls

  s2=''.join(ls) # convert from list of characters to string
  print "s2 = ",s2

  
main()
Technical Details
This reading is optional and is only provided to possibly answer some questions you may have about the __ methods. You do not need to know this material

Methods with names that begin with __ (like __add__) are special methods that usually have a simpler syntax that is cleaner than using method names. You probably already know the shortcuts, but for those that want to know more, you can also call these method names directly using x.__methodname__(argument) (where x is a string and the argument's type is appropriate for the given method). Using the alternate notation shown in the help documentation is the prefered way to use these methods. For example, for string concatenation use x + y instead of x.__add__(y). You can see that we have been using some of these special methods for quite awhile:

s = "hello"
y = s + " there"           # prefered syntax for string concatenation
y = s.__add__(" there")    # this does the same thing, but don't use this notation
print len(s)       # len(s) is also s.__len__()
Basically, when python sees x+y, it automatically rewrites the code as x.__add__(y). As programmers, the x+y syntax is usually cleaner, more natural, easier to write, and easier to understand.

For lists, the __ methods work similarly, e.g.,

l1 = [1, 2, 3, 17]
l2 = l1[2:4]        # prefered syntax for the slice operation
l2 = l1.__getslice__(2,4)  # this does the same thing, but has icky syntax