Flat_Eric Contemplating Data Type Conversions

String Indexes

Printing by Numbers.

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].

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

  1. Create a string variable of at least 6 characters.
  2. print(variable[:5])

STEP only

  1. Create a string variable of at least 6 characters.
  2. 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:

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..

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course