String Methods

Python Resources

Python Objects and Methods

We have used several of Python's built-in functions in our programs thus far, including print, input, str, int, float, and len. In this lesson, we are introduced to a similar feature in Python know as methods. Methods are similiar to functions, in that when you call them, they perform a specific task, but they are different from functions in that they can only perform these tasks on variables that contain an object of the class to which the method belongs.

Python is a pure object-oriented language, therefore everything stored in memory by Python is an object. When you create a variable in Python you are also creating an object that is stored in that variable. For example, the code

word = "friend"

instantiates a String object, "friend", and stores its reference in the variable word. A reference is the location in memory where an object resides.

Classes

An object consists of two main parts: attributes and methods. Attributes are the things that an object can store, such as the unicode characters that that make up a string. Methods are the things that an object can do. For example, a String object can call a method named upper that converts all of the characters of a string to uppercase letters. It is classes that determine the attributes and methods of an object. In other words, classes are the blueprints used to construct objects.

You will learn more object classes in future unit.

Calling a Method

Look at the following example.

word = "friend"
print(word.upper())

Here is the code's output.

FRIEND

The code above starts by creating a String object, "friend", and then stores the string's reference in a variable named word. With this String object reference, the varible word has the ability to call any of Python's String class methods using "dot notation" syntax. In this example, word calls the String class's upper method. This method returns a copy of the original string, but with all its letters capitalized. The code ends by having the print function display the new string on the console. String objects are immutable, therefore String methods cannot alter string objects. They can however, make a copy of the original string, with all of the calling method's modifications applied.

Lab Exercise

Write a Python program that sums the following list of money amounts rounded to two decimal places.

money = "$32.95, $95.06, $44.78, $56.25, $21.84"

Step 1: Remove the dollar sign in front of each amount.

Step 2: Turn a copy of the original string into 6 strings. One string for each money amount.

Step 3: Convert each value in the array to a float.

Step 4: Display the sum rounded to two decimal places.

Sample Run

$32.95, $95.06, $44.78, $56.25, $21.84
32.95, 95.06, 44.78, 56.25, 21.84

['32.95', ' 95.06', ' 44.78', ' 56.25', ' 21.84']

32.95
95.06
44.78
56.25
21.84

250.88