Looping Over Strings

In workshop 3 we saw an example, where we created a list by starting with an empty list and using a loop to repeatedly append items to our list. Here we are going to do the same to loop over a string and build a new string.

First we need to see how we can loop over a string easily. Let's examine this code:

In [2]:
s = "fun"
for ch in s:
    print(ch)
f
u
n

This is similar to the for item in list loop that we used in the workshop. The loop body executes three times (once for each letter in string s) and the variable ch becomes the next letter in s on each pass of the loop.

And we can use the variable ch in the body of the loop. Let's do something more interesting with ch than just print it. Let's build another string where we replace all the o's with *'s.

In [4]:
original = 'looping over strings'
result = ''
for ch in original:
    if ch == 'o':
        result = result + '*'
    else:
        result = result + ch
print(result)
l**ping *ver strings

Remember that we can use the + operator (the plus sign) to concatenate strings. Let's do one more example, where we write a function to reverse a string.

In [5]:
def reverse(original):
    ''' (str) -> (str)
    
    Return a string that is the reverse of original.
    >>>('Forward')
    'drawroF'
    
    '''
    result = ''
    for ch in original:
        result = ch + result
    return result

And call it on a couple of examples.

In [7]:
print(reverse('Forward'))
print(reverse('abc 123'))
drawroF
321 cba

Notice that inside the loop body, we concatenated ch to the front end of result.

This week's homework will give you practice looping over both strings and lists using both the for item in X and the for i in range(len(X)) loops.