Previous Lesson Table of Contents Next Lesson

We encountered lessons all the way back in lesson 1, but we never formally discussed them as a class. We intend to do that here in this lesson.

First, strings (denoted as the class str in Python) are also collections! They are collections of characters (e.g. "a", 1, etc.). Thus, they support indexing (with the bracket syntax we have seen before) and the len function:

s = "cat"
print(s[0])
print(len(s))

This will output:

c
3

However, it should be noted that strings are immutable. Thus, they do not support removing and adding elements.

Strings also support something called interpolation. To explain this concept, let’s look at an example. Suppose we want to print the phrase, "Welcome to the party, Bob!, for more people than just Bob. Based on what we know, we would have to write the same phrase over and over again, with a different name each time. Instead, we can write something more powerful:

welcome = "Welcome to the party, {}!"

print(welcome.format("Bob"))
print(welcome.format("Mary"))
print(welcome.format("Eric"))

This will output:

Welcome to the party, Bob!
Welcome to the party, Mary!
Welcome to the party, Eric!

Notice that instead of writing the same phrase over and over, we use a placeholder for the name, denoted by the {}. To fill in those placeholders, we call the format method and pass in a comma-delimited sequence of Python objects to fill in all of the {} that are in the string. In this case, there was one, so we only passed in one argument.

Here is one with two placeholders:

welcome = "Welcome to the party, {} and {}!"

print(welcome.format("Bob", "Mary"))

This will output:

Welcome to the party, Bob and Mary!

It is this populating of placeholders in a string that we can interpolation. This functionality is quite appealing because it reduces the likelihood of typographical errors (e.g. writing "part" instead of "party") because we reuse the same string template.

We should also point out that str is very universal amongst Python objects. That is because almost all Python objects have a string representation. How come? Because that’s what you output when you pass in an object to the print function!

You can explicitly get that string representation by passing the object into the __init__ method for str, as seen below:

l = [1, 2, 3]

print(l)
print(str(l))

This will output:

[1, 2, 3]
[1, 2, 3]

The string representation of [1, 2, 3] is just "[1, 2, 3]".

Let’s practice what we have learned with str so far:

  • Initialize a string with the value of dog. Print out its length. Then print out the last character. (solution)

  • Use placeholders to write the phrase, "My name is Bob.", with the following other names: "Mike", "John", "Anne", "Sarah". (solution)

  • Convert the set {1, 2, 3} to a string and print it out. (solution)

If you feel comfortable with strings, feel free to move on to the next lesson!