String Indexes
A string (str) in Python is an ordered sequence of characters. This means that strings are stored in the computer's memory as an ordered list where every character has a specific numerical position, known as an index.
If we have the string 'Toronto', the characters are stored in memory from 0 to 6. When you tell Python to print the string, it looks in memory for those characters in that exact order.
The Index Map
Just like we learned with formatted strings, programming begins counting at 0. Here is how Python "sees" the string 'Toronto':
| Character | T | o | r | o | n | t | o |
|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
Slicing: [START:STOP:STEP]
Understanding how to manipulate strings based on their index is a vital concept. When we use square brackets with colons, we are giving Python three specific instructions: [START : STOP : STEP].
- START: The index where you want to begin.
- STOP: The index where you want to end (Python stops just before this number).
- STEP: How many characters to "step" or skip over.
If we don't provide a STOP or STEP, the default is to go all the way to the end and step 1 at a time.
Examples of Slicing:
STOP only
- Create a string variable of at least 6 characters.
- print(variable[:5])
STEP only
- Create a string variable of at least 6 characters.
- print(variable[::2])
The Hidden Default:
print(variable[5]) is technically the same as saying print(variable[5:None:None]). It simply grabs the character at that specific spot and ignores the rest.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named string_indexes.py in your part14 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Extraction
Objective: Create a variable alphabet = "abcdefg". Use a single index to print the letter "c".
Exercise 2: Slicing the Start
Objective: Using the same alphabet variable, use slicing to print the first three letters (abc).
Exercise 3: The Leapfrog
Objective: Create a variable numbers = "0123456789". Use the STEP value to print only the even numbers (02468).
Exercise 4: The Mystery Word
Objective: Create a variable word = "Raincoat". Use slicing to extract and print only the word "coat".
Exercise 5: The Palindrome " A palindrome is a word, phrase, number, or sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. " Check
Objective: Use a negative STEP to determine if a word is the same forwards and backwards..
- Create a variable word1 = "racecar" and word2 = "python".
- Create a new variable for each called reverse1 and reverse2 by using a slice with a negative step.
- Challenge: In your comments (#), explain why word1 is considered a palindrome based on your output, but word2 is not.
- Print both results.
Don't Forget to commit and Push!