A2 - String and List Methods
In Python, all strings and lists are also objects that have many helpful built-in methods you can use. In addition to the introduction on this page, please see pages 9 and 10 of our Python Manual (also in the binders in the classroom).
Python's Built-In String Methods
Consider the following code:
# Create some strings
str1 = "Eastview"
str2 = "Secondary School"
str3 = "all lowercase"
str4 = "562"
# Test out some string methods
print(str3.capitalize()) # capitalize the first letter of str3
print(str2.count("c")) # how many c's in str2?
print(str1.islower()) # is str1 all lowercase?
print(str3.islower()) # is str3 all lowercase?
print(str4.isnumeric()) # is str4 a number?
print(str2.replace("Secondary", "High")) # in str2, replace "Secondary" with "High"
If you're interested in seeing some others, check out this page.
Python's Built-In List Methods
Consider the following code:
# Create a list
my_list = [2, 6, 5]
# Test out some list methods
my_list.append(6) # my_list becomes [2, 6, 5, 6]
print(my_list.count(6)) # prints 2, since the number six appears twice now in the list
my_list.extend([4, 8]) # my_list becomes [2, 6, 5, 6, 4, 8]
my_list.remove(6) # my_list becomes [2, 5, 6, 4, 8] (it deleted the first 6)
my_list.reverse() # my_list becomes [8, 4, 6, 5, 2]
my_list.sort() # my_list becomes [2, 4, 5, 6, 8]
Your Task
Part A
In your Unit-3 folder, create a file called a2a.py to complete this part in.
Write your own code to try out each of the methods that were introduced in the example, but this time use each of them in a slightly different way.
For instance, you could use the replace method to turn Eastview into Westview.
It might be easiest to start this one out by pasting in the sample code and then updating it.
ICS3U Students Only - Also try two additional string methods found in the Python Manual.
Part B
In your Unit-3 folder, create a file called a2b.py to complete this part in.
This is going to be similar to what you did with strings, but with lists instead. Use each of these methods on your own list of numbers. Change it up a bit by applying the methods in a different order and also changing the specific numbers.
ICS3U Students Only - Also try two additional list methods found in the Python Manual.