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
or python
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):
|
|
|
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:
|
To access certain letters of a string we can do the following:
|
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:
|
To join strings together (aka concatenate them) in Python we can do the following:
|
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.
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.