CPSC120A
Fundamentals of Computer Science I

Activity 16

Exploring the effect of string operators.

String Operations

Strings are a sequential data type; They are made up of sequence of smaller pieces of data. This is a very powerful structure to have, but it can also be a little confusing. Thankfully, Python allows us to basically treat Strings as if they were a primitive data type. This means all of our typical operators work, to an extent. To practice with the new object, work through the examples below.


Complete the following table. Which of the following operations work, and which do not?

Expression Expected Output Actual Output
"Hello" + "World"
"Hello" - "l"
"Hello" / "l"
"Hello" * "l"
"Hello" + 2
"Hello" - 2
"Hello" * 2
"Hello" / 2
"Hello"[2]

For each of the examples below, write what the program would output.

Sample Program Output
my_string = "Hello"
string_accumulator = ""
for i in range(len(my_string) -1, -1, -1):
    string_accumulator = string_accumulator + my_string[i]

print(string_accumulator)
my_string = "Hello, World"
string_accumulator = ""
for i in range(7, len(my_string)):
    string_accumulator = string_accumulator + my_string[i]

print(string_accumulator)
spam = "Spam"
spam_spam_spam = spam * 3
string_accumulator = ""
for i in range(len(spam_spam_spam)):
    string_accumulator = string_accumulator + spam_spam_spam[-i]

print(string_accumulator)