In this section we will discuss the basic ways that strings (i.e. words and sentences) can be manipulated in python. To get started, open up the python interpreter like we did earlier on in the lab (if you forgot, simply enter python3 into the shell). To create a string, set a variable to text enclosed in quotes as shown below (notice that assigning a variable does not return it's value, we must do that seperately):


>>> name = "Alonzo"
                    


>>> name
"Alonzo"
                    

Next, set a variable called name to your name (or the name of someone else). We can then use the len() function to get the length of the variable:


>>> name = "Alonzo"
>>> len(name)
6
                    

To access certain letters of a string we can do the following:


>>> name[0]
'A'
                    

Why is the first letter at position 0?
Notice that the output letter is actually surrounded in single quotes ('A'). We can also make strings using single quotes. The most important thing to notice is that the first letter is located at the "0th" position. Unlike in Snap! where the first letter was simply letter 1 of word, in python the first letter is at position 0. Having the first element at the 0th position is called "0 indexing" and is standard in most programming languages.

To get the last letter of a string we can do one of the following in python:


>>> name[len(name) - 1]
'o'
>>> name[-1]
'o'
                    

To join strings together (aka concatenate them) in python we can do the following:


>>> name + " says hello"
'Alonzo says hello'
                    

Note that using the + operator to join strings creates a new string and does not modify the old string. This means that joining two strings as shown above does not change the value of the variable name! You'll need to use the assignment operator (=) to actually change the value of a variable.

Substrings

In Python we can also easily create substrings of a string by using some special Python syntax as shown below (note that Snap! does not have a default function to do this):


>>> name[1:5]
'lonz'
>>> name[:3]
'Alo'
>>> name[3:]
'nzo'
>>> name[:3] + name[3:]
'Alonzo'
        

Substring [start:end] returns the letters in the word from start to end-1 (notice this is exactly how range(x, y) worked. The upper index value is not included), so always be careful with your indexing when using the substring and range functions.

Exercise 2

Write the function reverse_string(string) that takes in a string and puts it in the reverse order as shown below:


>>> reverse_string("Alonzo")
'oznolA'

        

You'll want to use some sort of loop, along with some of the things that you've learned about strings in this section. When you think your function works, run the tests that we have provided by entering the following command into the shell:


python3 autograder.py lab1.py