CPSC120A
Fundamentals of Computer Science I

Activity 17

Exploring string slice arguments and string traversal.

String Operations

The Python slice syntax is very powerful. Not only does it allow for extraction of portions of a string, but it also allows for much more complex types of extractions. The textbook does not demonstrate some of the more powerful portions of the slicing syntax; It allows negative arguments, has a third optional argument, and even handles the omission of arguments. In this activity you will explore some of these other uses of string slices.


Write how Python would evaluate each of the following expressions.

Expression Output
'Hello, World!'[6:11]
'Hello, World!'[6:-1]
'Hello, World!'[-6:-1]
'Hello, World!'[6:]
'Hello, World!'[:5]
'Hello, World!'[0:-1:2]
'Hello, World!'[4::-1]

Rewrite each of the functions below to use the for character in string style of loop.

Original Program Altered Program
def a_func(my_str):
    acc = ''
    for i in range(len(my_str)):
        char = my_str[i]
        if char != ' ':
            acc += char
    return acc
def a_func(my_str):
    vowels = 'aeiou'
    acc = ''
    for i in range(len(my_str)):
        char = my_str[i]
        if char in vowels:
            acc += '*'
        else:
            acc += char
    return acc
def a_func(my_str, your_str):
    acc = ''
    for i in range(len(my_str)):
        if my_str[i] != '*':
            acc += my_str[i]
        else:
            acc += your_str[i]
    return acc