So far we have a seen a couple of data structures in Python: strings and lists. They each support several methods, which are variants of functions.
For example, one method of list
s is the reverse()
method. As the name suggests, it reverses the list (for example the first item becomes the last and vice-versa). You call a method using a period (.
) structure like the following:
«objectName».«methodName»(«list of arguments, if any»)
For comparison, the syntax we have already seen for calling functions was
«functionName»(«list of arguments, if any»)
Here is an example of calling the reverse
method on a list.
An example of a method which takes an argument is str.startswith
:
Many Methods
Below we mention the most common methods for the string and list classes. These mostly perform tasks that you should be able to write yourself, but using standard methods has the benefit of making your code easier for others to read and edit.
Lists
These methods do not alter the list:
list.index(X)
: findX
in the list. Specifically, this returns ani
such thatlist[i]==X
by searching all items. The lowest possiblei
is returned. IfX
doesn't exist in the list, aValueError
is caused.X in list
returnsTrue
ifX
is an element of list, otherwiseFalse
. Using this can avoid aValueError
. (Notein
is an operator, not a method.)
list.count(X)
: returns a count of how many timesX
appears in the list
These methods alter the list:
list.append(X)
addsX
to the end of thelist
list.insert(i, X)
addsX
at positioni
list.extend(L)
adds a listL
of items to the endlist.remove(X)
removes the first occurence ofX
list.pop(i)
deletes & returns itemlist[i]
, whilelist.pop()
deletes & returns the last itemdel list[i]
deletes thei
th item oflist
(Note this is a "del
statement", not a method)list.reverse()
reverses the listlist.sort()
sorts the list
All methods above except pop
return None
. Some of these functions can also be called with slightly different arguments; for complete details see the section on list methods in the Python documentation. Lists also support complex subranges called "slices" which permit insertion and deletion of entire sublists, similar to the string[x:y:z]
notation we saw in previous lessons.
Strings
Just like with lists, you can use in
, index
and count
with strings. They are even more powerful, since they work with substrings too and not just finding individual characters:
S in T
is a bool indicating whether stringS
is a substring of stringT
S.index(T)
finds the first index ofS
whereT
is a substringS.count(T)
gives the number of nonoverlapping occurrences ofT
as a substring ofS
Here are some of the most commonly useful str
methods:
- Letter case:
capitalize, lower, upper, islower, isupper
- Characters:
isalpha, isdigit
- Padding:
center, ljust, rjust
;strip
will erase padding - Substrings:
endswith, startswith, find, replace
- Parsing:
split, splitlines
We will introduce these in more detail when needed. A complete detailed list of string methods is given in the Python documentation.
Strings are immutable. We mentioned list.reverse()
which changes a list by reversing it, but there is no str.reverse()
method. This is because string objects cannot be modified once they are created. In lesson 17 we explain a bit more about this.
Here is an example of a string method: S.replace(old, new)
returns a modified version of S
where every occurrence of substring old
has been replaced by new
. This creates a new string without altering the old one:
For the next exercise, the following methods are useful:
str.replace
, which we just described- the boolean method
str.isalpha()
which givesTrue
ifstr
is a string (or character) made of letters only - the boolean method
str.isdigit()
which givesTrue
ifstr
is a string (or character) made of digits only str.upper()
which returns a version ofstr
converted to upper case.
The rest of this lesson is a bit technical and not required knowledge for the remaining lessons. |
More About Objects
As you learn more about Python, you will encounter more classes than just strings and lists. Others which you are likely to find useful are file objects, sets, and dictionaries. They all have many useful methods. You can ask Python for all of the methods of a given object using the dir
function:
Looking at the properties of an object is called introspection. Everything in Python is allowed to have methods:
Some of the entries in dir
are actually member variables instead of methods, for example int.denominator
is a number and not a function. Technically, functions are objects in Python, so member functions are a special case of member variables.
You can do introspection on modules too. If you import math
and then call dir(math)
then you'll get a list of everything in the math
module, including the number pi
and the function sqrt
.
Why Objects?
Why do we have methods like S.index(T)
instead of just a simple function call like index(S, T)
? That is to say, why do we have the object S
and the method str.index()
at all?
The major advantages of objects become clearer as you start programming with more complex and varied types of data. Each type of object (i.e., the str
class) represents both the underlying data being stored (e.g., a sequence of characters and its length) and the types of operations that can be performed on it (e.g., converting to upper case or producing a substring). A more complex example are file objects: they represent the name of the file being opened, your current position in the file, and methods to read and write to them. You can even define your own data types!
This general approach is called "object-oriented programming" (OOP). Some of its benefits are:
- organization: Everything from the
math
module can be accessed bymath.«name»
syntax, avoiding the potential for overwriting existing variable names in your program. - encapsulation: Just like a program can work with several strings or several files at the same time, you can work with many distinct copies (instances) of the data type defined by any other class.
- re-use: Once you've defined a data type (like
str
) or a library of methods (likemath
) you can re-use it over and over again, or give it to other people to use. - debugging: Earlier, we saw how writing a function prevents the need for having many copies of similar code, which makes debugging easier. Writing all functions associated with a data type in a single place (the class definition) has the same effect.
- relations between classes: Python knows that the
index
method can mean one thing for a string and something else for a list. Likewise, not only can Python read and write files on your computer, but it can also read and write data on the Internet. In both cases (character or list sequences, and local or remote files) the related classes can be handled in a uniform way using the concept of inheritance.
In the rest of CS Circles we'll only be using objects and methods; you can learn more about creating your own classes later on (see the Resources page).
The next three lessons can be completed in any order, and they give a variety of challenges combining the topics from earlier lessons.