Lesson 02-02: Specific Letters with String Indexing¶
Length of a String¶
The len()
function is a function that will provide the length of a string. The length of a string is basically the number of characters in the string, spaces included. Here are a few quick examples:
Finding a Specific Letter in a String¶
We can point to a specific character within a string by using string indexing. Every letter, digit, space, or symbol in a string has a position in a string, also known as its index.
We use string indexing to reference a specific character in the string by using its index. The way that this is done is through brackets []
right after the string, with a number inside.
Try to predict what the following code will print:
Was it what you expected? If this is your first time seeing string indexing, you were probably off by one. That’s because strings use zero-based indexing, which is when the index always starts counting from zero, instead of one.
Here’s an example of the values of word[0]
, word[3]
, and word[6]
for a variable word = "POKEMON"
.
It’s worth noting that string indexing gives you a string as the result.
Please keep in mind that from this point on, this book will use 0-based indexing as well. So if you read “the 4th position” or “the 4th letter”, it is the same as saying “the 4th index”
What happens if you reference a position that’s greater than the length of the string itself? Try running the code and see:
Trying to reference a position that’s past the end of the string will give you an error! And it even gives us a descriptive error message as well. Use this to your advantage when you come across it.
Typically, to find the last character in a string without knowing what the string is going to be, we would use the expression word[len(word)-1]
. But in python, there’s an easier way.
Negative String Indexing¶
You can provide negative numbers as indexes as well. Its behavior is interesting. See the example below:
As you can see, when you provide a negative number, it starts counting from the end, with the last letter having an index of -1. This is very important because this allows us to use string indexing to things like “the second to last letter” of a string.
Checks For Understanding¶
Q#1¶
-
ch0202-1: With word = “duck tape”, what would the expression word[6] give us?
- (A) "p"
- Remember that spaces count!
- (B) "t"
- Don't forget to start counting from 0!
- (C) "A"
- There are no capitals in this string..
- (D) "a"
- Great job!
Q#2¶
-
ch0202-2: With word = “battery”, which ways can we access the last letter? Check all that apply.
- (A) word["last"]
- (B) word[-1]
- (C) word[len(word)-1]
- (D) word[6]
- (E) word[7]
- Don't forget to start counting from 0!
Q#3¶
-
ch0202-3: With word = “hello world”, which of the following will give an error?
- (A) word[5]
- (B) word[0]
- (C) word[11]
Q#4¶
In the following area, complete the code so that the output matches what is stated in the comments #
.