Using the Split Function

The split function does exactly that. It takes as input the character to split on, then returns a list with pieces. The pieces can then be indexed.

Try running this program.

    csp-17-3-1: What do you think we would get if we executed print(pieces[3])
  • Smith
  • That's pieces[1].
  • girl
  • That's pieces[2]
  • 65 Elm Street
  • The address is at position 3 in the resulting list.
  • eat
  • That's pieces[4]
  • We would get an error
  • Why would this cause an error? We can use indices to get the element at an index in a list.
    csp-17-3-2: What do you think we would get if we executed print(pieces[5])
  • Smith
  • That's pieces[1].
  • girl
  • That's pieces[2].
  • 65 Elm Street
  • That's pieces[3].
  • eat
  • That's pieces[4].
  • We would get an error
  • The error happens because that index is past the end of the list. The last item is at index 4.

The code below is the first activecode modified to use the split function to assign the values to the variables.

This makes it easy to change all of the data, by changing only one line as shown below.

Write code to print out the phone number without the area code using the ‘’split’’ function.

Show Comments

Note

Discuss topics in this section with classmates.

Show Comments
Next Section - Out of Range Error