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:
s = "fun"
for ch in s:
print(ch)
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.
original = 'looping over strings'
result = ''
for ch in original:
if ch == 'o':
result = result + '*'
else:
result = result + ch
print(result)
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.
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.
print(reverse('Forward'))
print(reverse('abc 123'))
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.