The original version was written by R. Jordan Crouser at Smith College, and it has been updated in Spring 2019/2020 by Alicia M. Grubb.
Take a few minutes and introduce yourself to your lab partner. Answer the question: “Assuming that you are all caught up in life and had a free day, what would you do?”
Steps 1-4 should be completed in the Shell
Declare a variable called s
, and initialize its value to "Smith College CS Department"
Use the print()
and len()
functions to display the following information on the console
:
The value of s is Smith College CS Department.
The length of s is 27 characters.
So far, we’ve only worked with strings in their entirety. However, there are many cases where it is useful to be able to work with a specific piece of a string.
Perform the following functions in the console.
We can think of strings as a list of letters:
If we want to print out each letter individually, we can use a loop:
test_string = "FALL2018"
# Print each letter individually
for letter in test_string:
print(letter)
If we only want the first letter, we can extract it using an index:
# Select only the first letter
print(test_string[0])
Or maybe we want to remove the 4 digits on the end, keeping only the first 4. We can do this using slicing, which is indicated using a colon “:
”:
# Keep the first 4 letters
print(test_string[:4])
Oops, or maybe we want to keep the last 4 instead of removing them:
# Keep the last 4 letters
print(test_string[-4:])
What if we wanted to print EVERY OTHER letter? We can do this by passing an optional third parameter to the slice using a second colon:
# Print every other letter
print(test_string[::2])
Try playing around with other step sizes. Negative values are allowed!
Python indexing feels really weird when you first encounter it. Why is the first item indexed with zero? Why is the last item in the slice not included?
It turns out this leads to some cool properties:
len(s[a:b])
is just b-a
s[:b] + s[b:]
gives us back s
len(s[-b:])
is b
Begin by downloading the short answer starter file (click this link), and save it locally. Open the file with either Thonny or a text editor. Answer the following short answer question (1-2 English sentences.):
SA Question #1: What are two applications where you would use indexing to get part of a string?
At this point you should switch driver/navigator roles.
Using the same s
(s = "Smith College CS Department"
) from Step 1, use slicing with a positive index to extract the first two words (“Smith College”) and save it to a variable called school
.
Again using the same s
, use slicing with a negative index to extract the last 13 letters (“CS Department”) and save it to a variable called department
.
Use the values stored in school
and department
to print the following to the console, but rather than counting the number of -
characters, use the len()
function to see how many you need:
+-----------------------------+
| Smith College CS Department |
+-----------------------------+
Strings
are objects
in Python
, and they have several useful methods that can be called on them. In this section, we’ll learn a little more about how they work.
.lower()
, .upper()
, and .capitalize()
The first three methods we’ll explore modify the case of a string (i.e. whether it is written with lowercase or uppercase letters).
To see this in action, try running the following commands in the console:
s = "aBcDeFg"
print("UPPERCASE:", s.upper())
print("lowercase:", s.lower())
print("Capitalize:", s.capitalize())
.split()
The .split()
method is useful for breaking a string into pieces. To see how this works, try the following:
sentence = """It was a bright cold day in April,
and the clocks were striking thirteen."""
print("Individual words:", sentence.split())
Because .split()
gives us back a list (see the square brackets?), we can use the results of a call to .split()
inside a loop. Note: We haven’t learned about loops yet, so we don’t expect you to fully understand the following code or use them in your lab/homework, but see if you get the general idea.
for word in sentence.split():
print(word)
Calling .split()
without anything inside the parentheses tells Python
that we want it to split the string on whitespace (spaces, tabs, etc.). However, we can choose to split on any delimiter we want by passing it in as input to the .split()
method:
print("Before and after the comma:", sentence.split(','))
(Notice the newline character \n
from where we hit return
in the multiline string!)
.join()
You can think of the .join()
method as the undo of the .split()
method: it uses copies of whatever string it is called on to concatenate the strings that are passed into it. For example:
words = sentence.split()
with_dashes = '-'.join(words)
print(with_dashes)
.replace()
The .replace()
method makes it really easy to (as its name implies) replace instances of one substring with another. For example, we could change all appearances of the letter 'a'
to 'oo'
:
phrase = "I like to eat apples and bananas"
print(phrase.replace('a', 'oo'))
Answer the following short answer question (1-2 English sentences) in your short answer question file for this lab:
SA Question #2: What is a real world example where you might use .split()
, .join()
, or .replace()
?
At this point you should switch driver/navigator roles.
Begin by downloading the lab starter file (click this link), and save it locally.
Declare a variable called phone_number
, and initialize its value to "2022243121"
Use any combination of operations, indexing, and methods to convert phone_number
’s format and print
it to the console as follows:
Phone number: (202) 224-3121
At this point you should switch driver/navigator roles.
Begin by downloading the lab starter file (click this link), and save it locally.
Declare five variables (name, filename, section, peers, and ref) and initialize them to be the appropriate values for your header in the starter file:
name = "Alicia"
filename = "lab2p6.py"
section = "L01"
peers = "N/A"
ref = "N/A"
Use these four variables along with any combination of techniques for manipulating strings to output a header similar to the one at the top of your starter file, but only with these five values and the border.
Pay particular attention to indentation / alignment!
This is an extra short lab! We encourage you to get started on your homework assignment in lab this week.
lab2SA.txt
, lab2p5.py
, and lab2p6.py
files before the end of the day.