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'
                    

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 very common in all other 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'
                    

Substrings

In Python we can also easily create substrings of a string by using some special Python syntax as a 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 3

Find exercise 3 in the virus.py file and modify 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 virus.py reverse_string